org.hibernate.TransientPropertyValueException - java

Please What did i wrong, and what should i do?
I have an org.hibernate.TransientPropertyValueException exeption during the compilation when i try to insert objects into my database:
Main class
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = new HibernateUtil().getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Role role = new Role();
role.setTitle("ex-president");
User user1 = new User(100,"Barack","Obama");
User user2 = new User(100,"Ronald","Reagan");
user1.setRole(role);
user2.setRole(role);
session.save(user1);
session.save(user2);
role.getUsers().add(user1);
role.getUsers().add(user2);
session.save(role);
session.getTransaction().commit();
session.close();
}}
HibernateUtil class
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
}
public SessionFactory getSessionFactory(){
return sessionFactory;
}}
Role class
#Entity
public class Role {
private Long role_id;
private String title;
private Set<User> users = new HashSet<User>();
public Role(){}
public Set<User> getUsers() {
return users;
}
public void addUser(User user){
users.add(user);
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Long getRole_id() {
return role_id;
}
public void setRole_id(Long id) {
this.role_id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}}
User class
#Entity
public class User {
private long user_id;
private int age;
private String firstname;
private String lastname;
private Role role;
public User(){
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public User(int age, String firstname, String lastname) {
this.age = age;
this.firstname = firstname;
this.lastname = lastname;
}
public long getUser_id() {
return user_id;
}
public void setUser_id(long id) {
this.user_id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="user.cfg.xml"/>
<mapping resource="role.cfg.xml"/>
</session-factory>
</hibernate-configuration>
role.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Role" table="role">
<id name="role_id" column="id">
<generator class="native"/>
</id>
<property name="title" column="TITLE"/>
<set name="users" cascade="all"
inverse="true" lazy="true" fetch="select">
<key column="id" not-null="true"/>
<one-to-many class="User"/>
</set>
</class>
</hibernate-mapping>
user.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="user">
<id name="user_id" column="user_id">
<generator class="native"/>
</id>
<property name="firstname" column="firstname"/>
<property name="lastname" column="lastname"/>
<property name="age" column="age"/>
<many-to-one name="role" class="Role" fetch="select">
<column name="id" not-null="true"/>
</many-to-one>
</class>
</hibernate-mapping>
Error information in log:

Your program maybe has many mistakes. At least these mistakes what I can point out:
Role role = new Role();
role.setTitle("ex-president");
User user1 = new User(100, "Barack", "Obama");
User user2 = new User(100, "Ronald", "Reagan");
user1.setRole(role);
user2.setRole(role);
session.save(user1);
session.save(user2);
role.getUsers().add(user1);
role.getUsers().add(user2);
session.save(role);
(1) Object role (an instance of class Role) hasn't role_id.
(2) Object user1, user2 hasn't role_id
(3) Must have few record of Role before save user1, user2, because these objects need foreign key (role_id).

Related

Error executing DDL via JDBC Statement

I really need some help in hibernate, and i search all questions,but it didn't work.
My question is strange,at least I think so. In my project, i want to use entity class, hibernate xml mapping file(*.hbm.xml) and hibernate configuration file(hibernate.cfg.xml) to create table in mysql database. Strange that I have only one table can not be created, and other tables can be created successfully.
OK,These are my project code, i think these information might be used.
cart.java
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* #author Ning
*
*/
public class Cart implements Serializable{
private Integer id;
private User user;
private Map<Integer, Integer> shopItems = new HashMap<>();
public Cart() {}
public Cart(User user, Map<Integer, Integer> shopItems) {
super();
this.user = user;
this.shopItems = shopItems;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Map<Integer, Integer> getShopItems() {
return shopItems;
}
public void setShopItems(Map<Integer, Integer> shopItems) {
this.shopItems = shopItems;
}
#Override
public String toString() {
return "Cart [id=" + id + ", user=" + user + ", shopItems=" + shopItems + "]";
}
}
<!------cart.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">
<!-- Generated 2017-4-30 9:23:54 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eshop.design.model.Cart" table="CART">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<many-to-one name="user" class="com.eshop.design.model.User" fetch="join">
<column name="USER" />
</many-to-one>
<map name="shopItems">
<key column="CART_ID"></key>
<index column="PRODUCT_ID" type="java.lang.Integer"></index>
<element column="NUMBER" type="java.lang.Integer"></element>
</map>
</class>
</hibernate-mapping>
Order.java
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Order implements Serializable{
private Integer id;
private User user;
private Map<Integer, Integer> shopItems = new HashMap<>();
private Date date;
private Status status;
private String remark;
public Order() {}
public Order(User user, Map<Integer, Integer> shopItems, Date date, Status status, String remark) {
super();
this.user = user;
this.shopItems = shopItems;
this.date = date;
this.status = status;
this.remark = remark;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Map<Integer, Integer> getShopItems() {
return shopItems;
}
public void setShopItems(Map<Integer, Integer> shopItems) {
this.shopItems = shopItems;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
#Override
public String toString() {
return "Order [id=" + id + ", user=" + user + ", shopItems=" + shopItems + ", date=" + date + ", status="
+ status + ", remark=" + remark + "]";
}
}
<!-------order.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">
<!-- Generated 2017-4-30 9:23:54 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eshop.design.model.Order" table="ORDER">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<many-to-one name="user" class="com.eshop.design.model.User" fetch="join">
<column name="USER" />
</many-to-one>
<map name="shopItems">
<key column="ORDER_ID"></key>
<index column="PRODUCT_ID" type="java.lang.Integer"></index>
<element column="NUMBER" type="java.lang.Integer"></element>
</map>
<property name="date" type="java.util.Date">
<column name="DATE" />
</property>
<many-to-one name="status" class="com.eshop.design.model.Status" fetch="join">
<column name="STATUS" />
</many-to-one>
<property name="remark" type="java.lang.String">
<column name="REMARK" />
</property>
</class>
</hibernate-mapping>
<!-----user.java------>
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class User implements Serializable{
private Integer id;
private String login;
private String pass;
private String name;
private String phone;
private String address;
private Double assets;
// Constructors
/** default constructor */
public User() {}
/** full constructor */
public User( String login, String pass, String name, String phone, String address, Double assets) {
super();
this.login = login;
this.pass = pass;
this.name = name;
this.phone = phone;
this.address = address;
this.assets = assets;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Double getAssets() {
return assets;
}
public void setAssets(Double assets) {
this.assets = assets;
}
#Override
public String toString() {
return "User [id=" + id + ", login=" + login + ", pass=" + pass + ", name=" + name + ", phone=" + phone
+ ", address=" + address + ", assets=" + assets + "]";
}
}
<!-----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">
<!-- Generated 2017-4-30 9:23:54 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eshop.design.model.User" table="USER">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="login" type="java.lang.String">
<column name="LOGIN" />
</property>
<property name="pass" type="java.lang.String">
<column name="PASS" />
</property>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="phone" type="java.lang.String">
<column name="PHONE" />
</property>
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
<property name="assets" type="java.lang.Double">
<column name="ASSETS" />
</property>
</class>
</hibernate-mapping>
<!-- I config the data source and session factory in the spring's configuration file applicationContext.xml-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="minPoolSize" value="${minPoolSize}" />
<property name="maxPoolSize" value="${maxPoolSize}" />
<property name="initialPoolSize" value="${initialPoolSize}" />
</bean>
<!-- SessionFactory config -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="mappingLocations" value="classpath:com/eshop/design/model/*.hbm.xml"></property>
</bean>
<!----hibernate.cfg.xml--->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
This is the first time I have asked questions here, some formats may be unsatisfactory.
Thanks in advance and forget my poor English.

Hibernate doesn't find Mapping-file: org.hibernate.UnknownEntityTypeException: Unable to locate persister

I'm using hibernate 5 and trying to save an object to my database. But for some reason, I'm always getting a
Exception in thread "main" org.hibernate.MappingException: Unknown entity: model.database.Customer.
For some reason, the Customer.hbm.xml is not being found. I really don't know why.
Customer.hbm.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.database.Customer" table="CUSTOMER">
<id name="username" type="string">
<column name="USERNAME" length="8" />
<generator class="assigned"></generator>
</id>
<property name="password" type="string">
<column name="PASSWORD" length="8" />
</property>
<property name="lastname" type="string">
<column name="LASTNAME" length="20" />
</property>
<property name="firstname" type="string">
<column name="FIRSTNAME" length="20" />
</property>
</class>
</hibernate-mapping>
Customer.java:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="CUSTOMER")
public class Customer implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="username", nullable=false)
private String username;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="password")
private String password;
public Customer () {
}
public Customer(String username) {
this.username = username;
}
public Customer(String username, String firstname, String lastname, String password) {
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.PostgreSQL81Dialect
</property>
<property name="hibernate.connection.driver_class">
org.postgresql.Driver
</property>
<property name="hibernate.connection.url">
jdbc:postgresql://localhost:5432/postgres
</property>
<property name="hibernate.connection.username">
postgres
</property>
<property name="hibernate.connection.password">
postgres
</property>
<property name="hibernate.current_session_context_class">
thread
</property>
<mapping resource="model/database/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main:
public class Main {
public static void main(String[] args) {
Customer cstm = new Customer("lebetyp", "peter", "ja", "ja");
CustomerManager mngr = new CustomerManager();
mngr.saveCustomer(cstm);
}
}
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
System.out.println("Initial SessionFactory creation");
} catch (Throwable ex) {
System.out.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
How can I get rid of this exception to make it work. Is there missing a dependency? Or what am I doing wrong?
Add this to your hibernate.cfg.xml
remove <mapping resource="model/database/Customer.hbm.xml"/> and add
<mapping class="Customer"></mapping>.
I hope your Customer class has JPA annotations like #Entity , #Id etc in it.

could not initialize proxy - no Session (Spring-Hibernate-one to one)

I have two tabeles and I want to fetch on update data from database.
users table(columns):
user_id - username - password - role_id(Foreign Key) - email
user_roles table(columns):
role_id - role
I want to list users in users.jsp . lets see my codes:
User.java
package com.terafast.manager.model;
public class User {
private int id;
private String username;
private String password;
private String email;
private Role role;
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
Role.java
package com.terafast.manager.model;
public class Role {
private int id;
private String role;
public Role() {
}
public Role(String role) {
this.role = role;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
User.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.terafast.manager.model">
<class name="User" table="users">
<id name="id" column="USER_ID">
<generator class="native" />
</id>
<property name="username" column="USERNAME" />
<property name="password" column="PASSWORD" />
<property name="email" column="EMAIL" />
<many-to-one name="Role" class="com.terafast.manager.model.Role"
unique="true" not-null="true" column="role_id" />
</class>
</hibernate-mapping>
Role.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.terafast.manager.model">
<class name="Role" table="user_roles">
<id name="id" column="role_id">
<generator class="native" />
</id>
<property name="role" />
</class>
</hibernate-mapping>
This part is from UserDAOImpl that create List of users:
#Override
#Transactional
public List<User> list() {
#SuppressWarnings("unchecked")
List<User> listUser = (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return listUser;
}
I already declared public List list(); in UserDAO interface.
This is the part that I send List of users to users.jsp from my Controller:
#RequestMapping("/users/show")
public ModelAndView handleRequest() throws Exception {
List<User> listUsers = userDao.list();
ModelAndView model = new ModelAndView("panel/users");
model.addObject("userList", listUsers);
return model;
}
In jsp file I list Users like this:
<c:forEach var="user" items="${userList}" varStatus="status">
<tr>
<td>${status.index + 1}</td>
<td>${user.username}</td>
<td>${user.email}</td>
<td>${user.role}</td>
<td>Edit
Delete
</td>
</tr>
</c:forEach>
So when I run this project as server I got this output:
Hibernate: select this_.USER_ID as USER_ID1_1_0_, this_.USERNAME as USERNAME2_1_0_, this_.PASSWORD as PASSWORD3_1_0_, this_.EMAIL as EMAIL4_1_0_, this_.role_id as role_id5_1_0_ from users this_
and then this error:
Jul 20, 2015 3:32:06 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
Could someone explain what is wrong with my program? And how can if I want to add or edit user, what should I do exactly?
By default, all associations are lazy in Hibernate (as opposed to JPA where to-one associations are eager by default).
Either make the association between User and Role eager (lazy="false"):
<many-to-one name="Role" class="com.terafast.manager.model.Role"
lazy="false" unique="true" not-null="true" column="role_id" />
or explicitly initialize the lazy associations which you intend to use out of the session boundaries:
#SuppressWarnings("unchecked")
List<User> listUser = (List<User>) sessionFactory.getCurrentSession().createCriteria(User.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
for (User user : listUser) {
Hibernate.initialize(user.getRole());
}
Then in users.jsp, you should use ${user.role.role} to access the value.
Your exception totally depends on Lazy and Eager loading.
Set the <many-to-one> relation with property of lazy with false in your user.hbm.xml file.
try this:
<many-to-one name="Role" class="com.terafast.manager.model.Role"
lazy="false" fetch="select" unique="true" not-null="true" column="role_id" />
and follow #Dragan Bozanovic answer.

is it possible to insert update and delete a view using hibernate with mysql as database if it possible suggest me a solution

The following code is for insert delete and update data in mysql database table name is student and i created a view using this student table can i perform insert update delete operations on this view if possible suggest me how
This code to retrieve object
package roseindia.tutorial.hibernate;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FirstExam {
public static void main(String[] args)
{
Session session = null;
try{
SessionFactory sessionFactory =newConfiguration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction transacton =session.beginTransaction();
System.out.println("Inserting Record");
Contact contact = new Contact();
//contact.setId(1);
contact.setFirstName("Vikas");
contact.setLastName("Kumar");
contact.setEmail("vikas#gmail.com");
session.save(contact);
//session.update(contact);
//session.delete(contact);
transacton.commit();
System.out.println("Done");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
code for persistence class
package roseindia.tutorial.hibernate;
public class Contact {
private String firstName;
private String lastName;
private String email;
private int id;
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setEmail(String string) {
email = string;
}
public void setFirstName(String string) {
firstName = string;
}
public void setLastName(String string) {
lastName = string;
}
public int getId() {
return id;
}
public void setId(int i) {
id = i;
}
}
mapping class
<hibernate-mapping>
<class name="roseindia.tutorial.hibernate.Contact" table="STUDENT">
<id name="id" type="int" column="ID" >
<generator class="increment"/>
</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>
configuration class
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.161/testdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</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>

Hibernate and mysql error : Cannot add or update a child row

i have a hibernate error wich sais :
15:32:48,554 DEBUG SQL:111 - insert into apurement.user (groupe_id, username, password, email) values (?, ?, ?, ?)
15:32:48,664 WARN JDBCExceptionReporter:100 - SQL Error: 1452, SQLState: 23000
15:32:48,664 ERROR JDBCExceptionReporter:101 -
Cannot add or update a child row: a foreign key constraint fails (apurement.user,
CONSTRAINT groupe_id FOREIGN KEY (groupe_id) REFERENCES groupe (groupe_id)
ON DELETE NO ACTION ON UPDATE NO ACTION)
the code is Logic.java for the session management:
package com.beans;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.*;
public class Logic {
protected Configuration cfg;
protected SessionFactory sfg;
protected Session s;
protected Transaction tx;
public Logic() {
this.init();
}
public void init() {
this.setCfg(new Configuration().configure());
this.setSfg(this.getCfg().buildSessionFactory());
this.setS(this.getSfg().openSession());
this.setTx(this.getS().beginTransaction());
}
public Configuration getCfg() {
return cfg;
}
public void setCfg(Configuration cfg) {
this.cfg = cfg;
}
public SessionFactory getSfg() {
return sfg;
}
public void setSfg(SessionFactory sfg) {
this.sfg = sfg;
}
public Session getS() {
return s;
}
public void setS(Session s) {
this.s = s;
}
public Transaction getTx() {
return tx;
}
public void setTx(Transaction tx) {
this.tx = tx;
}
}
the User class :
package com.beans;
// Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1
/**
* User generated by hbm2java
*/
public class User implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer userId;
private Groupe groupe;
private String username;
private String password;
private String email;
public User() {
}
public User(Groupe groupe, String username, String password, String email) {
this.groupe = groupe;
this.username = username;
this.password = password;
this.email = email;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Groupe getGroupe() {
return this.groupe;
}
public void setGroupe(Groupe groupe) {
this.groupe = groupe;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
the user.hbm :
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="User" table="user" catalog="apurement">
<id name="userId" type="java.lang.Integer">
<column name="user_id" />
<generator class="identity" />
</id>
<many-to-one name="groupe" class="com.beans.Groupe" fetch="select">
<column name="groupe_id" not-null="true" />
</many-to-one>
<property name="username" type="string">
<column name="username" length="45" not-null="true" />
</property>
<property name="password" type="string">
<column name="password" length="45" not-null="true" />
</property>
<property name="email" type="string">
<column name="email" length="45" not-null="true" />
</property>
</class>
</hibernate-mapping>
groupe.java :
package com.beans;
// default package
// Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Groupe generated by hbm2java
*/
public class Groupe implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer groupeId;
private String groupeName;
private String groupeRole;
private Set users = new HashSet(0);
public Groupe() {
}
public Groupe(String groupeName, String groupeRole) {
this.groupeName = groupeName;
this.groupeRole = groupeRole;
}
public Groupe(String groupeName, String groupeRole, Set users) {
this.groupeName = groupeName;
this.groupeRole = groupeRole;
this.users = users;
}
public Integer getGroupeId() {
return this.groupeId;
}
public void setGroupeId(Integer groupeId) {
this.groupeId = groupeId;
}
public String getGroupeName() {
return this.groupeName;
}
public void setGroupeName(String groupeName) {
this.groupeName = groupeName;
}
public String getGroupeRole() {
return this.groupeRole;
}
public void setGroupeRole(String groupeRole) {
this.groupeRole = groupeRole;
}
public Set getUsers() {
return this.users;
}
public void setUsers(Set users) {
this.users = users;
}
}
Groupe.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">
<!-- Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="Groupe" table="groupe" catalog="apurement">
<id name="groupeId" type="java.lang.Integer">
<column name="groupe_id" />
<generator class="identity" />
</id>
<property name="groupeName" type="string">
<column name="groupe_name" length="100" not-null="true" />
</property>
<property name="groupeRole" type="string">
<column name="groupe_role" length="45" not-null="true" />
</property>
<set name="users" table="user" inverse="true" lazy="true" fetch="select">
<key>
<column name="groupe_id" not-null="true" />
</key>
<one-to-many class="com.beans.User" />
</set>
</class>
</hibernate-mapping>
hibernate.cfg:
<?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 name="sf">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/apurement</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="com.beans.User" resource="com/beans/User.hbm.xml"/>
<mapping class="com.beans.Groupe" resource="com/beans/Groupe.hbm.xml"/>
</session-factory>
</hibernate-configuration>
i don't know what is going on.
You have a User that has a many-to-one mapping to a Groupe with not-null specified as true. You are trying to persist (insert) a User that does not have a Groupe.

Categories

Resources