I am new to Hibernate so please guide me.
I have 2 entities Companies & Employees. One Company should have many employees.
Employees Hibernate Mapping File
<hibernate-mapping>
<class name="com.hibernate.demo.Employees" table="employees">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="empId" type="int" column="emp_id">
<generator class="native"/>
</id>
<property name="empCId" column="emp_cid" type="int"/>
<property name="empName" column="emp_name" type="string"/>
<property name="empContact" column="emp_contact" type="int"/>
</class>
</hibernate-mapping>
Companies Hibernate Mapping File
<hibernate-mapping>
<class name="com.hibernate.demo.Companies" table="companies" >
<meta attribute="class-description">
This class contains the companies detail.
</meta>
<id name="compId" type="int" column="comp_id">
<generator class="native"/>
</id>
<set name="employees" cascade="all" >
<key column="emp_cid"/>
<one-to-many class="com.hibernate.demo.Employees" />
</set>
<property name="compName" column="comp_name" type="string"/>
<property name="compCity" column="comp_city" type="string"/>
</class>
</hibernate-mapping>
Hibernate Configuration File
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedbdemo</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">knowarth</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="employees.hbm.xml"/>
<mapping resource="companies.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Simple POJO Classes.
Employees.java
public class Employees {
public Employees(){}
private int empId;
private int empCId;
private String empName;
private int empContact;
//Getter & Setter
}
Companies.java
public class Companies {
public Companies(){}
private int compId;
private String compName;
private String compCity;
private Set<Employees> employees;
//Getter & Setter
}
I want to delete Company Record from the companies table and all the employees from that company should be deleted. But the problem I am facing is that Company Record is deleted by all the Employees Record relative to that Company aren't deleted.
Below is the Delete Code
public class CompanyDao {
Configuration cfg = new Configuration().configure("hibernate.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
Companies comp = new Companies();
Scanner compSc = new Scanner(System.in);
public void deleteComp(){
session.beginTransaction();
System.out.println("Enter Company ID to delete it");
int cmp_id = compSc.nextInt();
Companies company = new Companies();
company.setCompId(cmp_id);
session.delete(company);
session.getTransaction().commit();
return;
}
}
You can rely on the database for cascading the DELETE statement, in which case you need to change the mapping to:
<set name="employees" cascade="all" inverse="true" >
<key column="emp_cid" on-delete="cascade" />
<one-to-many class="com.hibernate.demo.Employees" />
</set>
If you don't want to change the mapping, you need to fetch the entity from the database and let Hibernate handle the children deletion:
public void deleteComp(){
session.beginTransaction();
System.out.println("Enter Company ID to delete it");
int cmp_id = compSc.nextInt();
Companies company = session.get(Companies.class, cmp_id);
session.delete(company);
session.getTransaction().commit();
return;
}
Related
I have a table modeled in a legacy .hbm.xml file.
The legacy code to retrieve a row uses an org.hibernate.Criteria to get a uniqueResult(). In migrating to Hibernate 5.x, Criteria is deprecated so I am trying to use CriteriaBuilder to achieve the same. However when I try to add restrictions (Hib 5.x) based on what worked previously (Hib 4.x) I get an IllegalArgumentException:
java.lang.IllegalArgumentException: Unable to locate Attribute with the the given name [xyzKey.plantName] on this ManagedType [com.foo.bar.Plant]
at org.hibernate.metamodel.model.domain.internal.AbstractManagedType.checkNotNull(AbstractManagedType.java:147)
at org.hibernate.metamodel.model.domain.internal.AbstractManagedType.getAttribute(AbstractManagedType.java:118)
at org.hibernate.metamodel.model.domain.internal.AbstractManagedType.getAttribute(AbstractManagedType.java:43)
at org.hibernate.query.criteria.internal.path.AbstractFromImpl.locateAttributeInternal(AbstractFromImpl.java:111)
at org.hibernate.query.criteria.internal.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:204)
at org.hibernate.query.criteria.internal.path.AbstractPathImpl.get(AbstractPathImpl.java:177)
Plant.hbm.xml:
<hibernate-mapping>
<class lazy="false" name="com.foo.bar.Plant" table="Plant">
<meta inherit="false" attribute="extends">com.foo.bar.PlantBase</meta>
<id name="id" type="integer" column="plantID" unsaved-value="null">
<meta inherit="false" attribute="scope-set">protected</meta>
<generator class="native" />
</id>
<component name="xyzKey" class="com.foo.bar.PlantKey">
<meta inherit="false" attribute="use-in-tostring">true</meta>
<property name="plantName" type="string" index="xyzKeyndx" unique-key="plantKey">
<column name="plantName" />
</property>
<property name="xyzRevision" type="string" index="xyzKeyndx" unique-key="plantKey">
<column name="xyzRevision" length="100"/>
</property>
</component>
<property name="active" type="java.lang.Boolean" index="xyzKeyndx">
<column name="active" not-null="true"/>
</property>
<property name="description" type="string" not-null="false">
<meta inherit="false" attribute="field-description">User specified description. Does not need to be unique.</meta>
<meta inherit="false" attribute="use-in-tostring">false</meta>
<column name="descr" not-null="false" />
</property>
<property name="location" type="string" not-null="true">
<column name="location" />
</property>
</class>
</hibernate-mapping>
Hibernate 4.x based code that works:
protected Plant selectPlant(Session session, PlantKey xyzKey)
{
Criteria c = session.createCriteria(Plant.class);
if (Util.isEmpty(xyzKey.getXyzRevision()))
{
SimpleExpression plantName = Restrictions.eq("xyzKey.plantName", xyzKey.getPlantName());
SimpleExpression active = Restrictions.eq("active", true);
c.add(Restrictions.and(plantName, active));
}
else
{
c.add( Restrictions.eq("xyzKey", xyzKey) );
}
Plant plant = (Plant)c.uniqueResult();
return plant;
}
Hibernate 5.x based code that fails:
protected Plant selectPlant(Session session, PlantKey xyzKey)
{
ElapsedTimer timer = new ElapsedTimer();
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Plant> criteriaQuery = criteriaBuilder.createQuery(Plant.class);
Root<Plant> root = criteriaQuery.from(Plant.class);
List<Predicate> restrictions = new ArrayList<>();
if ( FBCUtil.isEmpty(vpeKey.getVpeRevision()) )
{
restrictions.add(criteriaBuilder.equal(root.get("xyzKey.plantName"), xyzKey.getPlantName())); // FAILS HERE!
restrictions.add(criteriaBuilder.equal(root.get("active"), true));
}
else
{
restrictions.add(criteriaBuilder.equal(root.get("xyzKey"), xyzKey));
}
criteriaQuery.where(restrictions.toArray(new Predicate[restrictions.size()]));
Query<Plant> query = session.createQuery(criteriaQuery);
Plant plant = query.uniqueResult();
return plant;
}
Did you try
criteriaBuilder.equal(root.get("xyzKey").get("plantName"), xyzKey.getPlantName())
I have trying to read from my database using Hibernate but I am having a problem. Any help would be appreciated. It has to do with the fact that there is a set of Answers in a Question object and I'm not sure the implications this is having on the subject.
List<Question> questions = session
.createQuery("from Question where topic = :id")
.setParameter("id", topic)
.list();
Code:
<class name="cdd.model.Question" table="question">
<id column="question_id" name="questionID" type="org.hibernate.type.PostgresUUIDType">
<generator class="org.hibernate.id.UUIDGenerator"/>
</id>
<many-to-one class="cdd.model.User" column="submitted_by" name="submittedBy" not-null="true" lazy = "false"/>
<many-to-one class="cdd.model.Topic" column="question_topic" name="topic" not-null="true" lazy = "false"/>
<property column="title" name="title" type="org.hibernate.type.TextType"/>
<property column="correct_answer" name="correctAnswer" type="org.hibernate.type.TextType"/>
<property column="date_submitted" name="dateSubmitted" type="org.hibernate.type.TimestampType"/>
<property column = "approved" name = "approved" type = "org.hibernate.type.BooleanType"/>
<set cascade="all" name="answers" >
<key column="question_id" not-null="true" lazy = "false" />
<one-to-many class="cdd.model.Answer"/>
</set>
</class>
Java Class That was mapped:
public class Question {
UUID questionID;
User submittedBy;
Topic topic;
String title;
String correctAnswer;
Timestamp dateSubmitted;
boolean approved;
Set<Answer> answers;
/*Constructor, Getters and Setters*/
}
Error:
XML validation started.
Checking file:/Users/rhamblin/Desktop/CDDExamGen/src/hibernateMapping.hbm.xml...
Attribute "lazy" must be declared for element type "key". [69]
XML validation finished.
I have an object User, which has a List of UserDictionary. Each UserDictionary has a List of UserWords with cascade delete.
User.java
public class User implements Serializable
{
private Long id;
private String login;
private String password;
private String email;
private Boolean isVerified;
private List<UserDictionary> dictionaries = new ArrayList<>();
private UserTrainingSettings settings;
//getters and setters there
}
And mapping User.hbm.xml
<hibernate-mapping>
<class name="User" dynamic-insert="true" dynamic-update="true" table="USER" entity-name="user">
<id name="id" type="java.lang.Long" column="user_id">
<generator class="native"/>
</id>
<property name="login" type="java.lang.String" length="40" not-null="true" unique="true"/>
<property name="password" type="java.lang.String" length="32" not-null="true"/>
<property name="email" type="java.lang.String" length="100" not-null="true"/>
<property name="isVerified" type="java.lang.Boolean" column="verified" not-null="true"/>
<list name="dictionaries" fetch="join">
<key column="user_id" not-null="true" on-delete="cascade"/>
<one-to-many class="com.github.wordsmemoriser.Model.UserDictionary"/>
</list>
<one-to-one name="settings" class="com.github.wordsmemoriser.Model.UserTrainingSettings"
cascade="javax.persistence.CascadeType.REMOVE"/>
</class>
</hibernate-mapping>
UserDictionary.java
public class UserDictionary
{
private Long id;
private User user;
private String name;
private List<UserWords> words = new ArrayList<>();
//getters and setters there
}
And mapping UserDictionary.hbm.xml
<hibernate-mapping>
<class name="UserDictionary" dynamic-insert="true" dynamic-update="true" table="DICTIONARY">
<id name="id" type="java.lang.Long" column="dict_id">
<generator class="native"/>
</id>
<many-to-one name="user" class="com.github.wordsmemoriser.Model.User" fetch="join">
<column name="user_id" not-null="true"/>
</many-to-one>
<property name="name" type="java.lang.String" length="100"/>
<list name="words">
<key column="dict_id" not-null="true" on-delete="cascade"/>
<one-to-many class="com.github.wordsmemoriser.Model.UserWords"/>
</list>
</class>
</hibernate-mapping>
What is a proper way to delete all UserDictionaries from User? Should I iterate this list, delete every UserDictionary from database, then clear this list and update User like this
session.beginTransaction();
for(UserDictionary dict : user.getDictionaries())
{
session.delete(dict);
}
user.getDictionaries().clear();
session.update(user);
session.getTransaction().commit();
or should I just clear User's list and then update it like this
user.getDictionaries().clear();
session.beginTransaction();
session.update(user);
session.getTransaction().commit();
I have three objects USER, CONTACT and ACTION.
Each USER has many CONTACTS and each CONTACT has many ACTIONS
Each CONTACT and ACTION has status assigned to them, e.g. 20 or 60 or...
Please have a look at the data model.
Requirement is to get the CONTACTs having a particular status, or get the CONTACTs whose ACTIONs have that particular status.
E.g. get me CONTACTs with status 20, or CONTACTs who’s ACTIONs have status 20
At the moment I have the following query that is retrieving the CONTACTs with the status 20 and does not considers that status of the ACTIONs
USER
public class User {
private Integer userID;
private String userFirstName;
private String userLastName;
private Set<Contact> contactSet = new HashSet<Contact>();
private Set<Action> actionSet = new HashSet<Action>();
private ContactCriteria contactCriteria;
.
.
.
}
CONTACT
public class Contact implements Serializable {
private Integer contactID;
private Integer contactStatus = 0;
private String givenName;
private String familyName;
private String streetAddress;
private Set<User> userSet = new HashSet<User>();
private Set<Action> actionSet = new HashSet<Action>();
.
.
.
}
ACTION
public class Action implements Serializable {
private Integer actionID;
private Integer actionStatus;
private User user;
private String actionNote;
private Contact contact;
.
.
.
}
Following are my mapping files:
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.smallworks.model" schema="smallworksdb">
<class name="User" table="USERACCOUNT">
<id column="USER_ID" length="500" name="userID">
<generator class="increment"/>
</id>
<property column="USER_FIRSTNAME" generated="never" lazy="false" length="100" name="userFirstName"/>
<property column="USER_LASTNAME" generated="never" lazy="false" length="100" name="userLastName"/>
<set cascade="all" fetch="select" lazy="true" name="contactSet" sort="unsorted" table="USER_CONTACT">
<key column="USER_ID"/>
<many-to-many class="com.smallworks.model.Contact"
column="CONTACT_ID" order-by="CONTACT_ID" unique="false"/>
</set>
<!-- one to many mapping with Action -->
<set inverse="true" lazy="true" name="actionSet" sort="unsorted" order-by="ACTION_DUE_DATE" cascade="save-update">
<key column="USER_ID"/>
<one-to-many class="com.smallworks.model.Action"/>
</set>
<!-- one to one mapping with ContactCriteria -->
<one-to-one name="contactCriteria" class="com.smallworks.model.ContactCriteria"
cascade="save-update" lazy="false"></one-to-one>
</class>
</hibernate-mapping>
Contact.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.smallworks.model" schema="smallworksdb">
<class name="Contact" table="CONTACT">
<id column="CONTACT_ID" length="500" name="contactID">
<generator class="increment"/>
</id>
<property column="GIVEN_NAME" generated="never" lazy="false"
length="100" name="givenName"/>
<property column="FAMILY_NAME" generated="never" lazy="false"
length="100" name="familyName"/>
<property column="STREET_ADDRESS" generated="never" lazy="false"
length="100" name="streetAddress"/>
<property column="CONTACT_STATUS" generated="never" lazy="false"
name="contactStatus" type="integer"/>
<set inverse="true" lazy="false" name="userSet" sort="unsorted" table="USER_CONTACT">
<key column="CONTACT_ID"/>
<many-to-many class="com.smallworks.model.User" column="USER_ID" unique="false"/>
</set>
<!-- one to many mapping with Action -->
<set inverse="true" lazy="true" name="actionSet" sort="unsorted" order-by="ACTION_DUE_DATE" cascade="save-update">
<key column="CONTACT_ID"/>
<one-to-many class="com.smallworks.model.Action"/>
</set>
</class>
</hibernate-mapping>
Action.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.smallworks.model" schema="smallworksdb">
<class name="Action" table="ACTION">
<id column="ACTION_ID" length="500" name="actionID">
<generator class="increment"/>
</id>
<property column="ACTION_STATUS" generated="never" lazy="false"
name="actionStatus" type="integer"/>
<!-- many to one mapping with Contact -->
<many-to-one cascade="save-update"
class="com.smallworks.model.Contact" column="CONTACT_ID" lazy="false"
name="contact" not-null="true" />
<!-- many to one mapping with User -->
<many-to-one class="com.smallworks.model.User" column="USER_ID"
lazy="false" name="user" not-null="true"/>
</class>
</hibernate-mapping>
My existing query is:
Query query = session.createQuery("select distinct c FROM com.smallworks.model.User as u INNER JOIN u.contactSet as c WHERE u.userID=:userIDPara AND c.contactStatus in (:contactStatusPara)");
query.setParameter("userIDPara", user.getUserID());
query.setParameterList("contactStatusPara", statusList);
contactList = query.list();
Add an outer join on c.actions as a and an OR restriction on a.status.
select distinct c FROM com.smallworks.model.User as u INNER JOIN u.contactSet as c LEFT OUTER JOIN c.actionSet a WHERE u.userID=:userIDPara AND (c.contactStatus in (:contactStatusPara) OR a.actionStatus in (: actionStatusPara)
I have two objects User and Contact, with many to many relation, and I am using an intermediate table for this relation USER_CONTACT
Saving the data in this association is fine, but the retrieval is an issue.
I need to retrieve the data based on the User, but what I am getting is all the Contacts, for all the Users.
It will be good if you can let me know what wrong I am doing.
public class User {
private Integer userID;
private String userLoginEmail;
private String password;
private Set<Contact> contactSet = new HashSet<Contact>();
.
.
}
public class Contact implements Serializable {
private Integer contactID;
private String givenName;
private String familyName;
private Set<User> userSet = new HashSet<User>();
.
.
}
User.hbm.xml:
<class name="User" table="USERACCOUNT">
<id column="USER_ID" length="500" name="userID">
<generator class="increment" />
</id>
<property column="USER_LOGIN_EMAIL" generated="never" lazy="false" length="100" name="userLoginEmail" />
<property column="USER_FIRSTNAME" generated="never" lazy="false" length="100" name="userFirstName" />
<property column="USER_LASTNAME" generated="never" lazy="false" length="100" name="userLastName" />
<set name="contactSet" table="USER_CONTACT" inverse="false" lazy="false" fetch="select" cascade="all">
<key column="USER_ID"/>
<many-to-many column="CONTACT_ID" class="com.smallworks.model.Contact"/>
</set>
</class>
Contact.hbm.xml
<class name="Contact" table="CONTACT">
<id column="CONTACT_ID" length="500" name="contactID">
<generator class="increment"/>
</id>
<property column="GIVEN_NAME" generated="never" lazy="false" length="100" name="givenName"/>
<property column="FAMILY_NAME" generated="never" lazy="false" length="100" name="familyName"/>
<!-- many to many mapping with the User via User_Contact table -->
<set inverse="true" lazy="false" name="userSet" sort="unsorted" table="USER_CONTACT">
<key column="USER_ID"/>
<many-to-many class="com.smallworks.model.Contact" column="CONTACT_ID" unique="false"/>
</set>
</class>
and this is how I am trying to retrieve the data, which I think is not correct.
List contactList = session.createQuery("from Contact").list();
It will be good if I can know how to go about getting the Contacts based on the User.
// First, retrieve the user you want.
User user = (User) session.get(User.class, user_id_you_want);
// Second, get the contacts of that given user and add them to a list (optional)
List contacts = new ArrayList();
contacts.addAll(user.getContactSet());
return contacts;