Hibernate - how to selectively fetch associated properties? - java

I'm using Spring with hibernate.
The object I'd like to fetch is of class A, which has attribute - a set of object of class B, like
public class A {
private Integer aID;
private Set<B> bs;
private String fieldA1;
private String fieldA2;
// setters and getters
}
public class B {
private Integer bID;
private String fieldB1;
private String fieldB2;
// setters and getters
}
In the mapping file, within the class A mapping tag, I include,
<set name="bs" table="TABLE_B">
<key column="A_ID" />
<one-to-many class="com.proj.test.B"/>
</set>
Now I want to fetch the A object with the bs inside filtered with criteria that depends on value of fieldB1 and fieldB2. (not to fetch all B objects)
Any suggestions / answers?

Try out the following :
#Query(value = "Select a from A a where a.bs.fieldB1 YOUR_CONDITION")
List<A> findAWithFilteredB();

Related

setting an id autogenerate into an object

Sorry if my post is duplicated or the tittle doesn't describe the topics, because I don't know how to describe this in the tittle, I look on internet, but I didn't find the solution.
I am using Java and JPA. The problem is the next :
I have a class A with an autogenerated key :
class A{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private List<B> listB;
}
And the class B with the id of this clas:
class B {
#EmbeddedId
private Bid id;
private String att;
}
class Bid {
private int idA;
private String text;
}
In a controller I want to create an object A, the problem is when I created the object A, I need to create the object B where the id of B contains the id of A which is autogenerated, and it is created in the moment when the entity is mapped to de database, I dont't know how to set the id autogenerated of A into the idB, maybe I should query to de database asking what is the las id of classA, but it seem bad.
Thanks in advance
Your case is a derived identifier case, where your entity B's identity was derived from the primary key of A. You can use #MapsId annotation for this case and your entities can be restructured like this:
#Entity
public class A {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#OneToMany(mappedBy="a")
private List<B> listB = new ArrayList<B>();
...
}
#Entity
public class B {
#EmbeddedId
private BId id;
#ManyToOne
#MapsId("idA")
private A a;
...
}
#Embeddable
public class BId {
private int idA;
private String att;
...
}
This is how you would persist the entities:
A a = new A();
BId bid = new BId();
bid.setAtt("text"); // notice that the idA attribute is never manually set, since it is derived from A
B b = new B();
b.setId(bid);
b.setA(a);
a.getListB().add(b);
em.persist(a);
em.persist(b);
See sample implementation here.
It would be useful to know which is the case scenario you are trying to solve in general because the structure you are using seems unnecessarily complex.
What is your real goal?

HQL:Implicit Association joining not working

I am using Hibernate 3.2.5 for my application.
I have a Dept table and an Employees table.
Dept.java
private int deptId;
private String deptName;
private Map empMap = new HashMap();
//Getters and Setters
Employees.java
private int empId;
private String empName;
private int deptId;
private int age;
private String sex;
private Dept dept;
//Getters and Setters
Association between these two:
<map name="empMap" inverse="false" cascade="all">
<key column="DEPT_ID"></key>
<map-key formula="EMP_ID" type="integer"></map-key>
<one-to-many class="com.jdbc.Employees"/>
</map>
When I try the below statement:
Query hqlQuery = session.createQuery("from Dept dept where dept.empMap.empName = 'XYZ'");
I am getting the below exception:
org.hibernate.QueryException: illegal attempt to dereference collection [dept0_.DEPT_ID.empMap] with element property reference [empName] [from com.jdbc.Dept dept where dept.empMap.empName = 'XYZ']
Kindly let me know how to use the implicit join here. Reading the doc, I am not able to figure out what I am missing.
You are trying to access a collection like a property. You can do this instead:
from Dept dept inner join dept.empMap emp where emp.empName = 'XYZ'

get results of primary key table from foreign key table in hibernate

I am new to hibernate and trying to use Criteria.
I stuck in getting the results from 2 table ie table where primary-foreign key are in realtion.
I have Carpooler and SourceToDestinationDetails DTO, Now based on user search data I want to fill Carpooler Object, which contain SourceToDestinationDetails, but I am not getting it and don't know how to do it using Criteria API.
public class Carpooler implements Serializable{
private long carpoolerId;
private String drivingLicenceNumber=null;
private String userType=null;![enter image description here][1]
private User user=null;
private List<VehicleDetails> listOfVehicleDetails=null;
private List<SourceToDestinationDetails> listOfSourceToDestinationDetails=null;
private Date carpoolerCreationDate;
}
public class SourceToDestinationDetails implements Serializable{
private static final long serialVersionUID = -7158985673279885525L;
private long sourceToDestinationId;
private String sourcePlace=null;
private String destinationPlace=null;
private String inBetweenPlaces=null;
private String sourceLeavingTime=null;
}
This is what I wrote,
Criteria criteria1 = getSession().createCriteria(SourceToDestinationDetails.class);
criteria1.add(Restrictions.like("sourcePlace", "%" + from + "%"));
criteria1.add(Restrictions.like("destinationPlace", "%" + to + "%"));
List<SourceToDestinationDetails> listOfExactMatchCarpooler = criteria1.list();
through above Criteria API, I am only getting SourceToDestinationDetails DTO record, but now I need Carpooler record as well, I dont know how to get Carpooler record of matching Carpooler_id in SourceToDestinationDetails table.
I mean if user gives,
String from = "Bellandur";
String to = "Silk Board";
then result should be List<Carpooler> object, which contain all matching SourceToDestinationDetails list inside.
You can do that by Annotations. You can use #OneToMany annotation in your SourceToDestinationDetails class as below,
public class SourceToDestinationDetails implements Serializable{
private static final long serialVersionUID = -7158985673279885525L;
#Column
private long sourceToDestinationId;
#Column
private String sourcePlace=null;
#Column
private String destinationPlace=null;
#Column
private String inBetweenPlaces=null;
#Column
private String sourceLeavingTime=null;
#OneToMany(mappedBy = "carpooler_id", cascade = CascadeType.ALL)
private Set<Carpooler> carpoolers;
}
If you want to acheive the same thing using HIBERNATE XML. Declare the XML as below
<set name="carpoolers" table="source_destination"
inverse="true" lazy="true" fetch="select">
<key>
<column name="carpooler_id" not-null="true" />
</key>
<one-to-many class="com.test.Carpooler" />
</set>
In that case your model class will be
public class SourceToDestinationDetails implements Serializable{
private static final long serialVersionUID = -7158985673279885525L;
private long sourceToDestinationId;
private String sourcePlace=null;
private String destinationPlace=null;
private String inBetweenPlaces=null;
private String sourceLeavingTime=null;
private Set<StockDailyRecord> carpoolers =
new HashSet<StockDailyRecord>();
}
I usually prefer Annotations than ugly XML's

Hibernate Mapping issue

I've 3 tables: A, B and C. A holds a one-to- many relation with B and B holds a one-to-one relation with C. When I do a session.save(objA), a row will be created in A, many rows will be created in B referring to the id of A and one row should be created in C for each entry in B referring to the id of B.
Now the problem is, A and B are getting populated as expected, but in C, rows are getting populated but the column containing id of B is populated with null value.
Is it the problem with the mapping given in hbm.xml?
B.hbm.xml
<one-to-one name="propertyC" class="com.model.C"
cascade="all" fetch="join">
</one-to-one>
C.hbm.xml
<many-to-one name="propertyB" class="com.model.B"
column="B_ID" unique ="true" fetch="join" update="true" insert="true" cascade="all">
</many-to-one>
B.java
class B{
private Long id;
private C propertyC;
}
C.java
class C{
private Long id;
private Long bId;
private B propertyB;
}
If you have a oneToOne relation beetween B and C why this is defined like a manyToOne in the C mapping (and not a OneToOne) ?
Furthermore, if you have a bidirectional relationship, you have to define the mappedBy element of the relationship:
#Entity
private static class B {
#Id
private Long id;
#OneToOne
private C propertyC;
}
#Entity
class C {
#Id
private Long id;
private Long bId;
#OneToOne (mappedBy="propertyC")
private B propertyB;
}

JPA mapped model returns null elements with Composite-Keys

I have build my data model using JPA and am using Hibernate's EntityManager 3 to access the data. I used HSQLDB for testing (junit). I am using this configuration for other classes and have had no problems.
However, the latest batch of tables use a composite-key as the primary-key and I am not able to retrieve the populated row from the database when it is implemented. I don't get an error, the query simply returns null objects.
For example if I query (using jsql) "FROM Order o" to return a list of all orders in the table, my list.size() has the proper number of elements (2), but the elements are null.
I am hoping that someone with a sharper eye than I can discern what I am doing wrong. Thanks in advance!
The (simplified) tables are defined as:
CREATE TABLE member (
member_id INTEGER NOT NULL IDENTITY PRIMARY KEY);
CREATE TABLE orders (
orders_id INTEGER NOT NULL,
member_id INTEGER NOT NULL,
PRIMARY KEY(orders_id, member_id));
ALTER TABLE orders
ADD CONSTRAINT fk_orders_member
FOREIGN KEY (member_id) REFERENCES member(member_id);
The entity POJOs are defined by:
#Entity
public class Member extends Person implements Model<Integer>{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="MEMBER_ID", nullable=false)
private Integer memberId;
#OneToMany(fetch=FetchType.LAZY, mappedBy="member", cascade=CascadeType.ALL)
private Set<Order> orderList;
}
#Entity
#Table(name="ORDERS")
#IdClass(OrderPK.class)
public class Order extends GeneralTableInformation implements Model<Integer>{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ORDERS_ID", nullable=false)
private Integer orderId;
#Id
#Column(name="MEMBER_ID", nullable=false)
private Integer memberId;
#ManyToOne(optional=false, fetch=FetchType.LAZY)
#JoinColumn(name="MEMBER_ID", nullable=false)
private Member member;
#OneToMany(mappedBy="order", fetch=FetchType.LAZY)
private Set<Note> noteList;
}
OrderPK defines a default constructor and 2 properties (orderId, memberId) along with their get/set methods.
public class OrderPK implements Serializable {
private static final long serialVersionUID = 1L;
private Integer orderId;
private Integer memberId;
public OrderPK() {}
public OrderPK(Integer orderId, Integer memberId) {
this.orderId = orderId;
this.memberId = memberId;
}
/**Getters/Setters**/
#Override
public int hashCode() {
return orderId.hashCode() + memberId.hashCode();
}
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (!(obj instanceof OrderPK))
return false;
OrderPK other = (OrderPK) obj;
if (memberId == null) {
if (other.memberId != null) return false;
} else if (!memberId.equals(other.memberId))
return false;
if (orderId == null) {
if (other.orderId != null) return false;
} else if (!orderId.equals(other.orderId))
return false;
return true;
}
}
(sorry for the length)
the entityManager is instantiated in an abstract class which is then extended by my other DAOs
protected EntityManager em;
#PersistenceContext
public void setEntityManager(EntityManager em) {
this.em = em;
}
and is configured by a spring context configuration file
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
</bean>
My test class
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class OrderDaoTest {
#Autowired
protected OrderDao dao = null;
#Test
public void findAllOrdersTest() {
List<Order> ol = dao.findAll();
assertNotNull(ol); //pass
assertEquals(2, ol.size(); //pass
for (Order o : ol) {
assertNotNull(o); //fail
...
}
}
}
When I strip away the composite-key from the Order class I am able to retrieve data, I am not sure what I am doing incorrectly with my mapping or configuration. Any help is greatly appreciated.
After struggling with this problem for awhile longer I learned that I was configuring my Id properties in the wrong class.
Originally I was configuring orderId and memberId in the Order class
#Entity
#Table(name="ORDERS")
#IdClass(OrderPK.class)
public class Order extends GeneralTableInformation implements Model<Integer>{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ORDERS_ID", nullable=false)
private Integer orderId;
#Id
#Column(name="MEMBER_ID", nullable=false)
private Integer memberId;
However, I learned that if you are using an IdClass OR EmbeddedId that you must make the appropriate field annotations for your Id columns in the ID Class.
#Entity
#Table(name="ORDERS")
#IdClass(OrderPK.class)
public class Order extends GeneralTableInformation implements Model<Integer>{
#Id
private Integer orderId;
#Id
private Integer memberId;
}
public class OrderPK implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="ORDERS_ID", nullable=false)
private Integer orderId;
#Column(name="MEMBER_ID", nullable=false)
private Integer memberId;
}
With this change I was able to return the expected results with my test.
I had same kind of problem. I had to create backend on existing database, which had some tables without primary keys and with nullable columns (I know!!). This means that Hibernate entities for these kind of tables would have composite primary key consisting of all of the table columns.
When I queried the table rows through JpaRepository's findAll method, I would get a list of results where some of the results would be null values while others would be ok.
I finally found out that if some field of the composite key is null, it would render whole row as null result.
OrderPK defines a default constructor and 2 properties (orderId, memberId) along with their get/set methods.
I'm not sure this explains everything but... that's not enough. From the JPA 1.0 specification:
2.1.4 Primary Keys and Entity Identity
...
The following rules apply for composite primary keys.
The primary key class must be public and must have a public no-arg constructor.
If property-based access is used, the properties of the primary key class must be public or protected.
The primary key class must be serializable.
The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14, "EmbeddedId Annotation") or must be represented and mapped to multiple fields or properties of the entity class (see Section 9.1.15, "IdClass Annotation").
If the composite primary key class is mapped to multiple fields or properties of the entity class, the names of primary key fields or properties in the primary key class and those of the entity class must correspond and their types must be the same.
Could you please fix your OrderPK class to comply with the specification and try again?
As a side note, I wonder why you are using the loadTimeWeaver in your Spring configuration (since you're using Hibernate).
Update: I can't reproduce the problem... works as expected for me.

Categories

Resources