I'm running into significant difficulty getting my mapping file to work with a collection of elements via a foreign key in Hibernate. Java will try to load these files below and won't have any runtime exceptions, but the events table is never loaded as an object of an employee (it will remain null, but every other attribute loads from the DB). In my MySQL database, I have the following:
TABLE: Employees
Primary Key: username varchar
name varchar
areacode INTEGER
phone INTEGER
addressNumber INTEGER
addressLocation varchar
email varchar
TABLE: Events
Primary Key: ID INTEGER
startDate DateTime
endDate DateTime
customerName varchar
employeeUsername varchar
<?xml version="1.0"?>
<class name="Employee" table="Employees">
<id name="username" column="username" type="string"/>
<many-to-one name="contact" class="Contact" column="username" unique="false" update="false" insert="false" optimistic-lock="true" not-found="exception" embed-xml="true" />
</class>
<class name="Contact" table="Employees">
<id name="username" column="username" type="string"/>
<property name="name" column="name" type="string"/>
<property name="addressNumber" column="addressNumber" type="int"/>
<property name="areacode" column="areacode" type="int"/>
<property name="phone" column="phone" type="int"/>
<property name="addressLocation" column="addressLocation" type="string"/>
<property name="email" column="email" type="string"/>
</class>
<?xml version="1.0"?>
<class name="Event" table="Events">
<id name="ID" column="ID" type="int">
<generator class="assigned"/>
</id>
<property name="startDate" column="startDate" type="date"/>
<property name="endDate" column="endDate" type="date"/>
<property name="customerName" column="customerName" type="string"/>
</class>
<class name="Employee" table="Events" entity-name="Employee2">
<id name="username" column="employeeUsername" type="string"/>
<list name="events" cascade="all">
<key column="employeeUsername"/>
<list-index column="ID"/>
<one-to-many class="Event"/>
</list>
</class>
Assume the hibernate.cfg.xml file exists and works (If you feel this needs to be shown, please let me know). It does include both of the files in its mapping files part.
I have a feeling my error is probably in my declaration of the collection of events in my "list" declaration. Here are the Java classes:
package org.hibernate.employee;
import java.util.Date;
public class Event {
private int ID;
private Date startDate;
private Date endDate;
private String customerName;
public Event(){
System.out.println("blah");
}
/**
* #return the iD
*/
public int getID() {
return ID;
}
/**
* #param id the iD to set
*/
public void setID(int id) {
ID = id;
}
/**
* #return the startDate
*/
public Date getStartDate() {
return startDate;
}
/**
* #param startDate the startDate to set
*/
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
/**
* #return the endDate
*/
public Date getEndDate() {
return endDate;
}
/**
* #param endDate the endDate to set
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
/**
* #return the customerName
*/
public String getCustomerName() {
return customerName;
}
/**
* #param customerName the customerName to set
*/
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
/*
* File: Contact.java
*/
package org.hibernate.employee;
/**
* This class represents a Contact information for an Employee.
*
*/
public class Contact {
private int username; // the contact identifier in the database
private int areacode; // the contact areacode
private int phone; // the contact phone
private String name; // the contact's name
private int addressNumber; // the contact's address number
private String addressLocation; // the contact's address location
private String email; // the contact's email
/**
* Constructs a Contact object.
*/
public Contact() {
}
/**
* #return the areacode
*/
public int getAreacode() {
return areacode;
}
/**
* #param areacode the areacode to set
*/
public void setAreacode(int areacode) {
this.areacode = areacode;
}
/**
* #return the phone
*/
public int getPhone() {
return phone;
}
/**
* #param phone the phone to set
*/
public void setPhone(int phone) {
this.phone = phone;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the addressNumber
*/
public int getAddressNumber() {
return addressNumber;
}
/**
* #param addressNumber the addressNumber to set
*/
public void setAddressNumber(int addressNumber) {
this.addressNumber = addressNumber;
}
/**
* #return the addressLocation
*/
public String getAddressLocation() {
return addressLocation;
}
/**
* #param addressLocation the addressLocation to set
*/
public void setAddressLocation(String addressLocation) {
this.addressLocation = addressLocation;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
public String toString(){
String retVal = "";
retVal += "Address: " + this.addressNumber + " " + this.addressLocation + "\n";
retVal += "Email: " + this.email + "\n";
retVal += "Phone: " + this.areacode + " " + this.phone + "\n";
retVal += "Name: " + this.name + "\n";
return retVal;
}
public void setUsername(int username) {
this.username = username;
}
public int getUsername() {
return username;
}
}
/*
* File: Employee.java
*/
package org.hibernate.employee;
import java.util.List;
/**
* This class represents an Employee in a company database.
*
*/
public class Employee {
private String username; // the employee's username
private Contact contact; // the employee's contact information
private List events;
/**
* Constructs an Employee object.
*/
public Employee() {
super();
}
/**
* #return the username
*/
public String getUsername() {
return username;
}
/**
* #param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* #return the contact
*/
public Contact getContact() {
return contact;
}
/**
* #param contact the contact to set
*/
public void setContact(Contact contact) {
this.contact = contact;
}
/**
* #return the events
*/
public List getEvents() {
return events;
}
/**
* #param events the events to set
*/
public void setEvents(List events) {
this.events = events;
}
public String toString(){
String retVal = "";
System.out.println(events);
retVal += "Username: " + username + "\n";
retVal += "Contact: " + contact + "\n";
return retVal;
}
}
Your mappings are wrong for two (main) reasons:
Mapping both Employee and Contact to the same table that way is not going to work. many-to-one requires a foreign key (e.g. a separate column); you're trying to reuse the primary key instead.
Re-mapping Employee class to a different table isn't going to work either - table and class are incompatible. Using a different entity name prevents an immediate error, but that's not the appropriate usage of it.
What you should do instead is:
Map Contact as component.
Map collection of events directly on Employee as one-to-many association.
Something like:
<class name="Employee" table="Employees">
<id name="username" column="username" type="string"/>
<component name="Contact" class="Contact"> <!-- class attribute optional -->
<property name="name" column="name" type="string"/>
<property name="addressNumber" column="addressNumber" type="int"/>
<property name="areacode" column="areacode" type="int"/>
<property name="phone" column="phone" type="int"/>
<property name="addressLocation" column="addressLocation" type="string"/>
<property name="email" column="email" type="string"/>
</component>
<list name="events" cascade="all">
<key column="employeeUsername"/>
<list-index column="event_idx"/>
<one-to-many class="Event"/>
</list>
</class>
Note that list-index should really be a separate column in your table if you want to map list of events as ordered list; you can't map it to id. If you don't want to define it as a column, you can either map the list as <bag> instead (and, optionally, specify order-by attribute to sort that bag by) or map it as collection of composite elements where each Event will no longer be an independent entity. Whether or not that's applicable depends on your business requirements.
Related
I am new to Hibernate. I am trying a sample application. The only output I get whenever I run either of DataStore.java or FetchData.java
java.lang.ArrayIndexOutOfBoundsException: 0
at oracle.jdbc.driver.OracleSql.main(OracleSql.java:1032)
Am not able to find what causes this exception. The application is basic. Just creating two tables, one with Question ids and corresponding questions, another table with Answers with corresponding question ids as foreign key. This is my first try in hibernate. If any one can solve this problem, I will be indebted to them. Thanks in advance.
DataStore.java
import java.util.ArrayList;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DataStore {
public static void main(String[] args) {
Session session = new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Transaction t = session.beginTransaction();
ArrayList<String> list1 = new ArrayList<String>();
list1.add("java is a programming language");
list1.add("java is a platform");
ArrayList<String> list2 = new ArrayList<String>();
list2.add("Servlet is an Interface");
list2.add("Servlet is an API");
Question question1 = new Question();
question1.setQname("What is Java?");
question1.setAnswers(list1);
Question question2 = new Question();
question2.setQname("What is Servlet?");
question2.setAnswers(list2);
session.persist(question1);
session.persist(question2);
t.commit();
session.close();
System.out.println("success");
}
}
FetchData.java
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class FetchData {
public static void main(String[] args) {
Session session = new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory().openSession();
Query query = session.createQuery("from Question");
List<Question> list = query.list();
Iterator<Question> itr = list.iterator();
while (itr.hasNext()) {
Question q = itr.next();
System.out.println("Question Name: " + q.getQname());
// printing answers
List<String> list2 = q.getAnswers();
Iterator<String> itr2 = list2.iterator();
while (itr2.hasNext()) {
System.out.println(itr2.next());
}
}
session.close();
System.out.println("success");
}
}
question.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<class name="Question" table="Question">
<id name="id" type="int" column="id">
<generator class="increment"></generator>
</id>
<property name="qname" column="qname" type="string"></property>
<list name="answers" table="Answers">
<key column="id"></key>
<index column="type"></index>
<element column="answer" type="string"></element>
<one-to-many class="Answer" />
</list>
</class>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="connection.username">testuser</property>
<property name="connection.password">amudhan</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="question.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Question.java
import java.util.List;
public class Question {
private int id;
private String qname;
private List<String> answers;
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the qname
*/
public String getQname() {
return qname;
}
/**
* #param qname
* the qname to set
*/
public void setQname(String qname) {
this.qname = qname;
}
/**
* #return the answers
*/
public List<String> getAnswers() {
return answers;
}
/**
* #param answers
* the answers to set
*/
public void setAnswers(List<String> answers) {
this.answers = answers;
}
}
Answer.java
public class Answer {
private int id;
private String answer;
private String posterName;
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the answer
*/
public String getAnswer() {
return answer;
}
/**
* #param answer
* the answer to set
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/**
* #return the posterName
*/
public String getPosterName() {
return posterName;
}
/**
* #param posterName
* the posterName to set
*/
public void setPosterName(String posterName) {
this.posterName = posterName;
}
}
Edit: This problem comes only when I add the following part in the question.hbm.xml.
<list name="answers" table="Answers">
<key column="id"></key>
<index column="type"></index>
<element column="answer" type="string"></element>
<one-to-many class="Answer" />
Simple insertion, updation with a single class/table work just fine. More than one class or table with foreign-key, the exception pops out.
This seems to be a problem with OracleSQL. I'd suggest making sure you have the latest JDBC as this may have been patched.
I am working on java Web Project and have to insert user records in Table.
There is a requirement to add prefix to the ID column value in user table which means We have to add prefix like 'user' to value generated by sequence to get final value for id column as 'user00001' which is primary key for each new record which got inserted in Table.
I have created a sequence and DB trigger to populate the ID column when any record is inserted in DB to get above requirement satisfied. I am using Oracle 11g DB.
In my Web application,i have to use Hibernate to do DB related tasks like insert,update
I have following xml configuration for my Table
<hibernate-mapping>
<class name="UserProfile" table="USER_PROFILE">
<id name="id" type="string">
<column name="id"/>
<generator class="sequence">
<param name="sequence">USER_PROFILE_SEQ</param>
</generator>
</id>
<property name="firstName" type="string" column="FIRST_NAME"/>
<property name="middleName" type="string" column="MIDDLE_NAME"/>
<property name="lastName" type="string" column="LAST_NAME"/>
</class>
</hibernate-mapping>
And have created Java bean for User profile as follows
public class UserProfile {
private String id;
private String firstName;
private String middleName;
private String lastName;
public UserProfile() {
super();
}
/**
* #return the id
*/
public String getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* #return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* #param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* #return the middleName
*/
public String getMiddleName() {
return middleName;
}
/**
* #param middleName the middleName to set
*/
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
/**
* #return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* #param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Hibernate is using the sequence which i have assigned in xml mapping and getting the value but instead of populating id column value as sequence number i want it to take value generated by DB trigger which takes sequence value and add a prefix like 'user' to it before inserting the record in table.
So my question is how to populate Id column in hibernate with trigger generated value? As i am new to Hibernate, i downloaded latest hibernate version 4.2.7 distribution.Any help will be greatly appreciated.
Note : I cannot drop Triggers as its requirement from Application team.
Does this post help you? https://forum.hibernate.org/viewtopic.php?t=973262
In that post is presented custom generator class that lets database to assign id.
Mapping will be like this:
<id name="id" type="string">
<column name="id"/>
<generator class="jpl.hibernate.util.TriggerAssignedIdentityGenerator" />
</id>
I'm learning hibernate and when I run the following program, I get this message :
Hibernate: insert into contact (firstname, lastname, email, id) values (?, ?, ?, ?) but when I check the table, nothing seems to be inserted. What's the problem here ? Clearly the statement value field is null but why?
I have the following POJO:
public class Contact {
private String firstName;
private String lastName;
private String email;
private long id;
/**
* #return Email
*/
public String getEmail() {
return email;
}
/**
* #return First Name
*/
public String getFirstName() {
return firstName;
}
/**
* #return Last name
*/
public String getLastName() {
return lastName;
}
/**
* #param string Sets the Email
*/
public void setEmail(String string) {
email = string;
}
/**
* #param string Sets the First Name
*/
public void setFirstName(String string) {
firstName = string;
}
/**
* #param string sets the Last Name
*/
public void setLastName(String string) {
lastName = string;
}
/**
* #return ID Returns ID
*/
public long getId() {
return id;
}
/**
* #param l Sets the ID
*/
public void setId(long l) {
id = l;
}
}
and below are my hibernate config and hbm files:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/aneesh</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
<?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>
<class name="Contact" table="contact">
<id name="id" column="id" >
<generator class="assigned"/>
</id>
<property name="firstName" >
<column name="firstname" />
</property>
<property name="lastName">
<column name="lastname"/>
</property>
<property name="email" >
<column name="email"/>
</property>
</class>
</hibernate-mapping>
and here is my code to insert :
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;
public class HSession {
public static void main(String[] args) {
Session session = null;
try{
SessionFactory sessionGet = new Configuration().configure().buildSessionFactory();
session = sessionGet.openSession();
Contact contact = new Contact();
contact.setFirstName("xyz");
contact.setLastName("zyx");
contact.setEmail("x#xmail.com");
contact.setId(20);
session.save(contact);
}finally{
// Actual contact insertion will happen at this step
try {
session.flush();
session.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
You forgot the begin and commit the transaction.
session = sessionGet.openSession();
**Transaction tx= session.beginTransaction();**
Contact contact = new Contact();
contact.setFirstName("xyz");
contact.setLastName("zyx");
contact.setEmail("x#xmail.com");
contact.setId(20);
session.save(contact);
**tx.commit();**
Before you are saving the object you have to get the transaction and after saving the object you have to commit the transaction.
Transaction tx = session.beginTransaction();
session.save(contact);
tx.commit();
Use transaction in save.
session.getTransaction().begin();
session.save(contact);
session.getTransaction().commit();
you should do a commit for the insert to be reflected in database
try
session.getTransaction().commit();
after your
session.save(contact);
So Im writing a test application. I want to save collections within every collected class. Each collected class has a unieq list of Data. I cant save the data classes.
the error I am getting
ERROR: Referential integrity constraint violation: "FK2EEFAAF2485486: PUBLIC.DATA FOREIGN KEY(NUMBER) REFERENCES PUBLIC.COLLECTED(KEY) (4)"; SQL statement: insert into data (number, data) values (null, ?) [23506-170]
Main class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hibernatecollectiontest;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
/**
*
* #author ivan
*/
public class HibernateCollectionTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Session session = Util.getSessionFactory().openSession();
Collected temp = new Collected();
temp.setDescription("test");
List<Data> local= new ArrayList<>();
for(int i=0;i<5;i++)
{
Data test = new Data();
test.setData("Data"+i);
local.add(test);
}
temp.setDatas(local);
session.beginTransaction();
session.save(temp);
session.getTransaction().commit();
Criteria crit = session.createCriteria(Collected.class);
List<Collected> dump =crit.list();
for(int i = 0 ; i < dump.size();i++)
{
System.out.println(dump.get(i).getKey()+" key "+dump.get(i).getDescription() +" describe ");
System.out.println("Size of collection is "+dump.get(i).getDatas().size());
for(int n=0;n<dump.get(i).getDatas().size();n++)
{
System.out.println(dump.get(i).getDatas().get(n).getData());
}
}
//session.flush();
}
}
The persistent class :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hibernatecollectiontest;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author ivan
*/
public class Collected
{
private String description;
private int key;
private List<Data> datas = new ArrayList<>();
/**
* #return the description
*/
public String getDescription() {
return description;
}
/**
* #param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* #return the key
*/
public int getKey() {
return key;
}
/**
* #param key the key to set
*/
public void setKey(int key) {
this.key = key;
}
/**
* #return the datas
*/
public List<Data> getDatas() {
return datas;
}
/**
* #param datas the datas to set
*/
public void setDatas(List<Data> datas) {
this.datas = datas;
}
}
Data class inside the collection :
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hibernatecollectiontest;
/**
*
* #author ivan
*/
public class Data
{
private int number;
private String data;
/**
* #return the number
*/
public int getNumber() {
return number;
}
/**
* #param number the number to set
*/
public void setNumber(int number) {
this.number = number;
}
/**
* #return the data
*/
public String getData() {
return data;
}
/**
* #param data the data to set
*/
public void setData(String data) {
this.data = data;
}
}
Hibernate Mappings :
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">
jdbc:h2:testdatabase
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.autocommit">true</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="Collected.hbm.xml"/>
<mapping resource="Data.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Data.hbm
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibernatecollectiontest">
<class name="Data" table="data">
<id name="number" column="number" type="java.lang.Integer">
<generator class="native"/>
</id>
<property column="data" name="data" type="java.lang.String"/>
</class>
</hibernate-mapping>
Collected.hbm
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="hibernatecollectiontest">
<class name="Collected" table="collected">
<id name="key" column="key" type="java.lang.Integer">
<generator class="native"/>
</id>
<property column="description" name="description" type="java.lang.String"/>
<list name="datas" table="data" lazy="false" cascade="all">
<key column="number"/>
<list-index column="sortOrder"/>
<one-to-many class="hibernatecollectiontest.Data"/>
</list>
</class>
</hibernate-mapping>
To start with.,
Transaction is not getting committed.,
//session.getTransaction().commit();
Above line is commented in the code base.,
I have this problem that i can't solve, this is my entity class:
/**
* #hibernate.class
* table="users.network_topic"
* #hibernate.cache usage="read-write"
*/
public class NetworkTopic implements Serializable, Idable{
/** identifier field */
private Long id;
/** persistent field */
private Long networkId;
/** persistent field */
private Long topicId;
private UserTopic topic;
private Network network;
/**
* #hibernate.id
* generator-class="assigned"
* type="java.lang.Long"
* column="id"
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
* #hibernate.property
* type="java.lang.Long"
* column="network_id"
* not-null="true"
*/
public Long getNetworkId() {
return networkId;
}
public void setNetworkId(Long networkId) {
this.networkId = networkId;
}
/**
* #hibernate.property
* type="java.lang.Long"
* column="user_topic_id"
* not-null="true"
*/
public Long getTopicId() {
return topicId;
}
public void setTopicId(Long topicId) {
this.topicId = topicId;
}
/**
* #hibernate.set
* lazy="true"
* inverse="true"
* cascade="none"
* #hibernate.key
* column="user_topic_id"
* #hibernate.one-to-many
* class="com.netblue.matchpoint.domain.UserTopic"
*
*/
public UserTopic getTopic() {
return topic;
}
public void setTopic(UserTopic topic) {
this.topic = topic;
}
/**
* #hibernate.set
* lazy="true"
* inverse="true"
* cascade="none"
* #hibernate.key
* column="network_id"
* #hibernate.one-to-many
* class="com.netblue.matchpoint.domain.Network"
*
*/
public Network getNetwork() {
return network;
}
public void setNetwork(Network network) {
this.network = network;
}
#Override
public String toString() {
return "Network[id=" + id + "]";
}
}
Then i try to save a new register with this code:
UserTopic topic = new UserTopic();
topic.setId(topicId);
topic.setName(ParseUtil.getString(map.get(MPConstants.TOPIC_NAME_PARAM)));
topic.setCreatedBy(ParseUtil.getInt(map.get(MPConstants.USER_ID)));
Date now = new Date();
topic.setCreatedDt(now);
topic.setLastUpdatedDt(now);
topic.setStatusId(Status.ACTIVE);
topic.setActivityCnt(0);
userTopicDao.saveOrUpdate(topic);
UserTopicMap utm = new UserTopicMap();
utm.setId(topicId);
utm.setMtid(topicId);
utm.setOtid(topicId);
utm.setIsDeleted(false);
utm.setLastUpdatedDt(now);
userTopicMapDao.saveOrUpdate(utm);
Network network = MpAuctionUtil.getNetworkById(networkId);
NetworkTopic networkTopic = new NetworkTopic();
networkTopic.setNetworkId(networkId);
networkTopic.setTopicId(topicId);
networkTopic.setNetwork(network);
networkTopic.setTopic(topic);
LOG.debug("userTopicService addObjSubscriber x networkId="+networkId+", topicId="+topicId);
networkTopicDao.saveOrUpdate(networkTopic);
The last lines are the ones that fail, if i remove them it works, i mean it saves topics ok, but when i try to do this it fail, i don't know if i'm doing something wrong, please help me !!
The NetworkTopic class hasnt been assigned an id. you must use the setId method or consider consider one of the other id strategies
2.2.3.1. Generating the identifier property
NetworkTopic networkTopic = new NetworkTopic();
networkTopic.setNetworkId(networkId);
networkTopic.setTopicId(topicId);
networkTopic.setNetwork(network);
networkTopic.setTopic(topic);
LOG.debug("userTopicService addObjSubscriber x networkId="+networkId+", topicId="+topicId);
networkTopicDao.saveOrUpdate(networkTopic);
Here,you must call the method setId, and set the value manually, because your id generator is "assigned", and that means you must assigned manually every time before you insert or update your data!