Apache ignite query from set - caching

is it possible to query values from set? for example,
public class Employee implements Serializable {
/** Person ID (indexed). */
#QuerySqlField(index = true)
private long id;
/** Department ID (indexed). */
#QuerySqlField(index = true)
private Set deptIds;
/** First name (not-indexed). */
#QuerySqlField
private String firstName;
/** Last name (not indexed). */
#QuerySqlField
private String lastName;
}
now i want to get all employee for one particular department.

It is possible with Scan queries, but not possible with SQL queries.
Looks like you use SQL queries. In this case you have to think in terms of relational databases. There is a many-to-many relationship between Employee and Department, so you have to add a Junction Table.
public class EmployeeDepartment implements Serializable {
/** Person ID (indexed). */
#QuerySqlField(index = true)
private long personId;
/** Department ID (indexed). */
#QuerySqlField(index = true)
private long deptId;
}
After that you can do a three way join to find employees for a particular department.

Related

Spring Data JDBC many to many relationship management

I have a many-to-many relationship person -> person_address <- address and use a reference class. But in my Person aggregate root it seems only adding person_address works (addresses collection):
#MappedCollection(idColumn = "PERSON_ID")
private Set<PersonAddress> addresses;
public void addAddress(final Address address) {
Assert.notNull(getId(),"Person ID cannot be null");
Assert.notNull(address.getId(),"Address ID cannot be null");
addresses.add(new PersonAddress(address.getId()));
}
I want to be able to delete from addresses collection and then do a save, but this doesn't work. So instead I use:
#Modifying
#Query(value = "delete from person_address where person_id = :personId and address_id = :addressId")
void deletePersonAddressById(#Param("personId") final Long personId, final Long addressId);
Is this the best way to handle this?
#ToString
#EqualsAndHashCode
#Getter
#Setter
public class PersonAddress {
/**
* Timestamp generated by database.
*/
#ReadOnlyProperty
#Setter(AccessLevel.NONE)
private LocalDateTime created;
private Long addressId;
public PersonAddress(final Long addressId) {
this.addressId = addressId;
}
}
You should be able to just remove entries from Person.addresses and save the entity again.
I created a sample to demonstrate this on GitHub.
On pitfall I fell into in the past was to not properly implement equals and hashCode for PersonAddress, which is of course important, when you want to remove instances from a HashSet or similar.

JPA CrudRepository save() not populating primary key after save

I have very strange issue here. I am using composite primary key with #IdClass in my entities. It is working fine in every case, except save. After saving the entity, JPA is not firing SELECT query to select inserted data, and not merging the result. Though data is getting saved in database successfully. Also there are no errors. Below is some of the code which can help in debugging the issue:
AbstractEntity.java
#MappedSuperclass
#IdClass(PrimaryKey.class)
public abstract class AbstractEntity implements Serializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -1191422925622832672L;
/** The id. */
private String id;
...
/**
* Gets the id.
*
* #return the id
*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public String getId() {
return id;
}
...
}
PrimaryKey.java
public class PrimaryKey implements Serializable {
/** The id. */
private String id;
/**
* Gets the id.
*
* #return the id
*/
#Column(name = "id")
#Convert(converter = CryptoConverter.class)
public String getId() {
return id;
}
...
}
User.java
#Entity
#Table(name = "user")
public class User extends AbstractEntity {
...
}
UserRepository.java
#Repository
public interface UserRepository extends CrudRepository<User, PrimaryKey> {
}
I have BigInt autoIncrement Id in database as primary key. But I want to expose it in encrypted form to outside world, so I have used #Converter to encrypt and decrypt it.
When I invoke userRepository.save(userEntity) from UserService, it persists the data, but does not return generated id from database.
How can I resolve this issue?
EDIT:
I have hosted demo project with this functionality here.
Since I am not seeing anywhere in your code, you need to specify Id, the strategy type and the column on the database.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "applicant_id")

Query method to searchin related collection

public class Trader {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
public String name;
public String title;
public String email;
public String phone;
public String address;
#OneToMany
public Set<Trader> customers;
}
I need an auto generated query method to search among customers names of a given trader.
Sql query is :
SELECT trader.name FROM trader WHERE trader.id IN
(SELECT * FROM trader AS t
INNER JOIN trader_customers AS tc ON tc.trader_id = t.id
WHERE t.id = 'Trader ID')
Need somethin like
findInCustomersByName(#Param("trader") Trader trader, #Param("name") String name)
You can use simple JPQL like
"select t.customers from Trade t where t.name= :name"
It gives you a list of Trade Objects and then get names of the respective objects.

EntityNotFoundException in Hibernate Many To One mapping however data exist

I'm getting an error
Caused by: javax.persistence.EntityNotFoundException: Unable to find tn.entities.AgenceBnq with id 01
when I get AgenceBnq through Employee
Employee class:
#Table(name = "EMPLOYEE")
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.employeMat = ?1"),
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "EMPLOYEE_MAT", unique = true, nullable = false, length = 15)
private String employeeMat;
...
#ManyToOne
#JoinColumn(name = "AGENCE_COD")
private AgenceBnq agenceBnq;
}
#Entity
#Table(name="AGENCEBNQ")
public class AgenceBnq implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="AGENCE_COD", unique=true, nullable=false, length=10)
private String agenceCod;
...
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="agenceBnq")
private Set<Employee> employees;
}
I'm calling namedQuery Employee.findById in DAO to retrieve data and I have to get AgenceBnq from Employee but get this error while calling query.getResultList()
#NotFound( action = NotFoundAction.IGNORE) isn't useful for me because data exist in AGENCEBNQ table and I have to retrieve date through Employee.
Is this a bug in hibernate ? I'm using hibernate version 3.6.7.Final
Firstly, You dont need query for it, the EnityManger.find(Employee.class, YOUR_ID) will do the job.
Secondly dont use ? in your queries but names (e.employeMat = :id) as it is easier to debug and less error prones for complicated queries.
Finally, check your DB table if the AGENCE_COD column in Employee table really contains the valid ID for your entitity that crashes (and that it length matches the ID length of AgenceBnq). It should work, the typical reason why it doesnt will be that your Employe.AGENCE_COD has defualt value and when creatubg the new EMploye you add it only to the Agence but you did not set Agence in the Employ.

hibernate Mapping One to many relation ship between primary key and composite key

I am struggling with a hibernate mapping problem of mapping One to many relation ship between Primary key of Order Table and composite key of Product Cart with some extra columns
public class OrderDetails implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="ORDERID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer orderId;
#Column(name="ORDER_DATE")
private Date orderDate= new Date();
//other fields and getter setter
.....
.....
Product Cart table has a composite key CART ID and PRODUCT ID
#Entity
#Table(name="PRODUCT_CART")
#AssociationOverrides({
#AssociationOverride(name="pk.shopCart", joinColumns=#JoinColumn(name="CARTID")),
#AssociationOverride(name="pk.product", joinColumns=#JoinColumn(name="PRODUCTID"))
})
public class ProductCart implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EmbeddedId
private ProductCartId pk = new ProductCartId();
#Column(name="QUANTITY")
private Integer selectedQuantity=1;
#Column(name="TOTAL")
private double total=0.0;
//other fields and getter setter
.....
.....
I tried following but not working
#Entity
#Table(name="PRODUCTCART_ORDERDETAILS")
#AssociationOverrides({
#AssociationOverride(name="pcoPK.orderDetails",joinColumns=#JoinColumn(name="ORDERID")) ,
#AssociationOverride(name="pcoPK.pk", joinColumns=
{#JoinColumn(name="pk.shopCart",referencedColumnName="CARTID"),
#JoinColumn(name="pk.product",referencedColumnName="PRODUCTID") }) })
public class ProductCartOrder implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2348674131019001487L;
#EmbeddedId
private ProductCartOrderId pcoPK = new ProductCartOrderId();
#Column(name="QUANTITY")
private Integer quantity;
#Column(name="PRICE")
private double price;
#Transient
public OrderDetails getOrderDetails(){
return getPcoPK().getOrderDetails();
}
public void setOrderDetails(OrderDetails orderDetails){
getPcoPK().setOrderDetails(orderDetails);
}
#Transient
public ProductCartId getProductCartId(){
return getPcoPK().getPk();
}
public void setProductCartId(ProductCartId pk){
getPcoPK().setPk(pk);
}
Can someone please help me to implement this? Below is the error message
Caused by: org.hibernate.AnnotationException: Illegal attempt to define a #JoinColumn with a mappedBy association: pcoPK.pk
at org.hibernate.cfg.Ejb3JoinColumn.buildJoinColumn(Ejb3JoinColumn.java:152)
at org.hibernate.cfg.Ejb3JoinColumn.buildJoinColumns(Ejb3JoinColumn.java:127)
at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:1212)
at org.hibernate.cfg.AnnotationBinder.fillComponent(AnnotationBinder.java:1841)
at org.hibernate.cfg.AnnotationBinder.bindId(AnnotationBinder.java:1878)
After lot of research I could not find the solution I done it in another way.
I created Many to many relationship between OrderDetails and Product with some extra columns ID, price, quantity and inserted value manually for each element in product cart thorugh a for loop.
public class Product implements Serializable {
#OneToMany(mappedBy="product")
private Set<ProductOrder> productOrder;
...//other fields and getter setter
}
public class OrderDetails implements Serializable {
#OneToMany(mappedBy="orderDetails")
private Set<ProductOrder> productOrder;
...//other fields and getter setter
}
public class ProductOrder {
#Id
#Column(name="PRODUCT_ORDER_ID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int prductOrderId;
#ManyToOne
private OrderDetails orderDetails;
#ManyToOne
private Product product;
...//other fields and getter setter
}
In my controller class where I wanted to save the products of ProductCart I did following
List<ProductCart> productList = new ArrayList<ProductCart>();
productList=productCartService.getCartProducts(shopCart);
ProductOrder orderedProducts = new ProductOrder();
for (ProductCart productCarts : productList) {
orderedProducts.setOrderDetails(orderDetails);
orderedProducts.setProduct(productCarts.getPk().getProduct());
orderedProducts.setPrice(productCarts.getPk().getProduct().getPrice());
orderedProducts.setQuantity(productCarts.getSelectedQuantity());
productOrderService.addOrderProducts(orderedProducts);
}

Resources