I have a form where i input details, but when i click on save it does not get saved in the database... though the table does get created.
My Contact POJO
package your.intermedix.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="USER")
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String email;
private String lastname;
private String designation;
#Id
#GeneratedValue
#Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="DESIGNATION")
public String getDesignation(){
return designation;
}
public void setDesignation(String designation){
this.designation = designation;
}
#Column(name="EMAIL")
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
#Column(name="LASTNAME")
public String getLastname(){
return lastname;
}
public void setLastname(String lastname){
this.lastname= lastname;
}
#Column(name="FIRSTNAME")
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String toString()
{
return "designation = '" + designation + "',email='"+ email +"', lastname='"+ lastname +"', name = '" + name + "'";
}
}
My Application-Context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Turn on AspectJ #Configurable support -->
<context:spring-configured />
<context:property-placeholder location="classpath*:*.properties" />
<context:component-scan base-package="your.intermedix"/>
<context:annotation-config/>
<!-- enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="txManager"/>
<!-- a PlatformTransactionManager is still required -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- (this dependency is defined somewhere else) -->
<property name="dataSource" ref="myDataSource"/>
</bean>
<!-- Turn on #Autowired, #PostConstruct etc support -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>your.intermedix.domain.Contact</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/spring"/>
<property name="username" value="monty"/>
<property name="password" value="indian"/>
</bean>
</beans>
I am not getting any sort of error.... in the console.
Updated code..
package your.intermedix.services;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Service;
import your.intermedix.domain.Contact;
import your.intermedix.services.IContact;
#Service
public class ContactSerImpl implements IContact {
private HibernateTemplate hibernateTemplate;
public void setSessionFactory(SessionFactory sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
#Transactional
public void saveContact(Contact contact) {
System.out.println("Hello Guru contact");
System.out.println(contact);
hibernateTemplate.saveOrUpdate(contact);
}
public void hello() {
System.out.println("Hello Guru");
}
}
My Service class where i the print statements work
You need a running transaction. Spring transaction management is the way to go if using HibernateTemplate. Read the documentation. It's too long to include in an answer, but here is in short:
you need to define a transaction manager as a spring bean
you need <tx:annotation-driven />
you need to annotate your transactional methods with #Transactional
I don't know the Spring-Hibernate framework, but often when data is not written it menas it is not flushed to the databackend. What gives you
System.err.println(hibernateTemplate.getFlushMode());
Related
Why am I getting error as below:
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'sessionFactory' defined in
ServletContext resource [/WEB-INF/spring-mvc-crud-demo-servlet.xml]:
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: No identifier specified for entity:
springmvc.miniproject.entity.Review
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name="reviews")
public class Review {
private int id;
private String reviews;
#ManyToMany(fetch=FetchType.LAZY,cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST,CascadeType.REFRESH})
#JoinColumn(name="id")
private Course course;
public Review() {}
public Review(int id, String reviews) {
// super();
this.id = id;
this.reviews = reviews;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReviews() {
return reviews;
}
public void setReviews(String reviews) {
this.reviews = reviews;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
}
package springmvc.miniproject.entity;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="courses")
public class Course {
#Id
#Column(name="id")
private int id;
#Column(name="Course_name")
private String courseName;
#OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL)
#JoinColumn(name="course_id")
private List<Review> review;
public Course() {}
public Course(int id, String courseName) {
this.id = id;
this.courseName = courseName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public List<Review> getReview() {
return review;
}
public void setReview(List<Review> review) {
this.review = review;
}
}
package springmvc.miniproject.DAO;
import java.util.List;
import springmvc.miniproject.entity.Course;
public interface CourseDAO {
public List<Course> getAllCourses();
}
package springmvc.miniproject.DAO;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springmvc.miniproject.entity.Course;
import springmvc.miniproject.entity.InstructorPersonalInfo;
import springmvc.miniproject.entity.Review;
import springmvc.miniproject.DAO.Instructor;
import springmvc.miniproject.controller.InstructorDetails;
#Repository
public class CourseDAOImpl implements CourseDAO,ReviewDAO {
#Autowired
private SessionFactory factory;
#Override
#Transactional
public List<Course> getAllCourses() {
System.out.println("getAllCourses");
//get current session
Session session = factory.getCurrentSession();
//create query
Query<Course> query = session.createQuery("from Course", Course.class);
//execute query
List<Course> course = query.getResultList();
if (course == null) {
System.out.println("null returned from query");
} else {System.out.println(course);}
return course;
}
#Override
public List<Review> getReviewForACourse(int courseId) {
// TODO Auto-generated method stub
return null;
}
}
-----------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="springmvc.miniproject" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/hb_tution_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="hbstudent" />
<property name="password" value="hbstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="initialPoolSize" value="5"/>
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="springmvc.miniproject.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js, etc ... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>```
org.hibernate.AnnotationException: No identifier specified for entity: springmvc.miniproject.entity.Review
Looks like you are missing #Id annotation on Review entity
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: Customer is not
mapped [from Customer]
while everything is fine why it is showing this error
Bean class:
package com.luv2code.springdemo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
//#Table(schema = "web_customer_tracker", name = "customer")
#Table(name="customer")
#Entity
public class Customer {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#Column(name="email")
private String email;
public Customer() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
DAO Impl class:
package com.luv2code.springdemo.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.luv2code.springdemo.entity.Customer;
#Repository
public class CustomerDAOImpl implements CustomerDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public List<Customer> getCustomers() {
//get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
//List customers = new ArrayList<Customer>();
//create a query
Query<Customer> theQuery=currentSession.createQuery("from customer", Customer.class);
//currentSession.createQuery("from Customer", Customer.class);
//execute query and get result list
List<Customer> customers=theQuery.getResultList();
// return the results
/* Customer cus1=new Customer();
cus1.setEmail("a#gmail.com");
cus1.setFirstName("Abhishek");
cus1.setId(10);
cus1.setLastName("Kumar");
customers.add(cus1); */
return customers;
}
}
DATABASE:
XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC" />
<property name="user" value="springstudent" />
<property name="password" value="springstudent" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
</beans>
It is because you are giving entity name in your Customer Entity,thus, same should be used in your queries(now name of the class cannot be referred in your queries). Try invoking the query with the same entity name mentioned(take care of cases as well).
Try as follows:
Query<Customer> theQuery=
currentSession.createQuery("from customer", Customer.class);
Here I have matched the entity name mentioned in #Entity(name="customer") in your query.
I didnt go through all your code but, in sessionFactory bean of xml,
Try changing <property name="packagesToScan" value="com.luv2code.springdemo.entity" /> to <property name="packagesToScan" value="code.luv2code.springdemo.entity" />.
Your actual Customer entity lives in package code.luv2code.springdemo.entity
, though you have used com.luv2code.springdemo.entity. So it is scanning wrong package. This might be the problem.
if you are using check if the packages of C3p0 of correct for hibernate, Iam using the following and it works for me.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.4.26.Final</version>
</dependency>
Also in contrast to the above answers, In Hibernate it is always the entity name for HQL even though you have added #Table(name="customer")
Query<Customer> theQuery=
currentSession.createQuery("from Customer", Customer.class);
Let me know if this still does not work for you
Try like this :
Query theQuery=currentSession.createQuery("from Customer");
In Customer class
#Entity --> hibernate takes by Default as #Entity(name = "Customer")
though your database table is customer it reads as Customer because annotated class hibernate configures as Customer
so update,
List<Customer> li = session.createQuery("from Customer").list();
I am trying to create a project with embedded h2 db, and using spring framework with hibernate. My database will be created in initialize time if not exist. My development platform is intellij.
Problem is that when i run the application
#Autowired
private IPersonService personService; // comes null?
here is my classes and config files.
myDB.sql:
CREATE TABLE IF NOT EXISTS personel(
id IDENTITY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age VARCHAR(100));
hibernate.properties:
db.driverClassName=org.h2.Driver
db.url=jdbc:h2:~/h2SpringProject/database/SpringSample;mv_store=false;mvcc=false
db.username=admin
db.password=
here is my hibernate-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.springapp"/>
<context:annotation-config/>
<context:property-placeholder location="hibernate.properties"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.SingleConnectionDataSource">
<property name="driverClassName" value="${db.driverClassName}"></property>
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
<property name="suppressClose" value="true"/>
</bean>
<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
<jdbc:script location="myDb.sql"/>
</jdbc:initialize-database>
<bean id="hibernateCfgProperties"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">
org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
</prop>
</props>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties" ref="hibernateCfgProperties"/>
<property name="packagesToScan" value="com.springapp.model"/>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
Person class
#Entity
#Table(name = "personel")
public class Personel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "age")
private String age;
.......
An IPersonDao interface and here is implemented class
#Component
public class PersonelDaoImpl implements IPersonelDao {
#Autowired
private SessionFactory sessionFactory;
public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void savePersonel(Personel personel) {
getCurrentSession().saveOrUpdate(personel);
}
#Override
public void deletePersonel(long id) {
getCurrentSession().delete(id);
}
#Override
public List<Personel> getPersonels() {
return getCurrentSession().createQuery("from Personel").list();
}
}
There is an IPersonService interface and here is implemented class
#Service("PersonelService")
public class PersonelServiceImpl implements IPersonelService {
#Autowired
private IPersonelDao personelDao;
#Override
#Transactional
public void savePersonel(Personel personel) {
personelDao.savePersonel(personel);
}
#Override
#Transactional
public void deletePersonel(long id) {
personelDao.deletePersonel(id);
}
#Override
#Transactional
public List<Personel> getPersonels() {
return personelDao.getPersonels();
}
}
here is my main class
public class MainApp {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = new ClassPathXmlApplicationContext("hibernate-config.xml");
ForExample a = new ForExample();
a.execute();
}
}
#Component
public class ForExample {
#Autowired
private IPersonelService personelService;
public void execute(){
Personel p = new Personel();
p.setName("thats Ok!");
p.setAge("614345");
personelService.savePersonel(p);
}
}
public class MainApp {
public static ApplicationContext applicationContext;
private static IPersonelService personelService;
public static void main(String[] args) {
applicationContext = new ClassPathXmlApplicationContext("hibernate-config.xml");
personelService = applicationContext.getBean(IPersonelService.class);
Personel p = new Personel();
p.setName("thatsOK!");
p.setAge("614345");
personelService.savePersonel(p);
}
}
Because of spring does not recognise new operator in run time..
I have some code on Spring/Hibernate/Jersey. I want Hibernate to generate my tables. This is my User entity
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
private String email;
private String nickname;
private String password;
#OneToOne(cascade=CascadeType.ALL)
private PersonalInfo personalInfo;
#OneToOne(fetch=FetchType.LAZY ,cascade=CascadeType.ALL)
private AccountInfo accountInfo;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public PersonalInfo getPersonalInfo() {
return personalInfo;
}
public void setPersonalInfo(PersonalInfo personalInfo) {
this.personalInfo = personalInfo;
}
public AccountInfo getAccountInfo() {
return accountInfo;
}
public void setAccountInfo(AccountInfo accountInfo) {
this.accountInfo = accountInfo;
}
public User(){
}
}
And this is my configuration:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<tx:annotation-driven/>
<context:component-scan base-package="com.weproj" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/DB" />
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.weproj.model"/>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
It generates the tables when the #GeneratedValue(strategy=GenerationType.IDENTITY) is removed but it does not when I set it.
If you want to use generated value for primary key or something like that try to use Integer in both the table structure and Java.
private String id;
try to make it
private int id;
make sure you have designed the User table similarly(Integer and auto generated ).
I really want to understand what is going on with my code.
I have a standalone application which uses spring and Hibernate as JPA and I am trying to run the test using a single main Class
My main class
package edu.acct.tsegay.common;
import edu.acct.tsegay.model.User;
import edu.acct.tsegay.business.IUserBusinessObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
try {
ApplicationContext context = new ClassPathXmlApplicationContext(
"Spring3AndHibernate-servlet.xml");
IUserBusinessObject userBusinessObject = (IUserBusinessObject) context
.getBean("userBusiness");
User user = (User) context.getBean("user1");
user.setPassword("pass");
user.setUsername("tsegay");
System.out.println(user.getPassword());
userBusinessObject.delete(user);
User user2 = new User();
user2.setUsername("habest");
user2.setPassword("pass1");
System.out.println(user2.getPassword());
/*
* userBusinessObject.save(user2);
*
* User user3 = userBusinessObject.searchUserbyId("tsegay");
* System.out.println("Search Result: " + user3.getUsername());
*/
System.out.println("Success");
} catch (Exception e) {
e.printStackTrace();
}
}
}
my application context is:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- data source -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="test" />
<property name="password" value="password" />
</bean>
<!-- session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- exposed person business object -->
<bean id="userBusiness" class="edu.acct.tsegay.business.UserBusinessObject">
<property name="userDao" ref="userDao" />
</bean>
<bean id="user1" class="edu.acct.tsegay.model.User">
<property name="username" value="tse" />
<property name="password" value="pass" />
</bean>
<!-- Data Access Object -->
<bean id="userDao" class="edu.acct.tsegay.dao.UserDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
My User Model is:
package edu.acct.tsegay.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Version;
import org.hibernate.annotations.NaturalId;
#Entity
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private Integer VERSION;
#Version
public Integer getVERSION() {
return VERSION;
}
public void setVERSION(Integer vERSION) {
VERSION = vERSION;
}
#NaturalId
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;
}
}
My DAO is:
package edu.acct.tsegay.dao;
import edu.acct.tsegay.model.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
#Repository
public class UserDao implements IUserDao {
private SessionFactory sessionFactory;
private HibernateTemplate hibernateTemplate;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
this.hibernateTemplate = new HibernateTemplate(sessionFactory);
}
public void save(User user) {
// TODO Auto-generated method stub
// getHibernateTemplate().save(user);
this.hibernateTemplate.save(user);
}
public void delete(User user) {
// TODO Auto-generated method stub
this.hibernateTemplate.delete(user);
}
public User searchUserbyId(String username) {
// TODO Auto-generated method stub
return this.hibernateTemplate.get(User.class, username);
}
}
And this my stacktrace error when i run the program:
pass
org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: edu.acct.tsegay.model.User; nested exception is org.hibernate.MappingException: Unknown entity: edu.acct.tsegay.model.User
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:679)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:837)
at org.springframework.orm.hibernate3.HibernateTemplate.delete(HibernateTemplate.java:833)
at edu.acct.tsegay.dao.UserDao.delete(UserDao.java:34)
at edu.acct.tsegay.business.UserBusinessObject.delete(UserBusinessObject.java:30)
at edu.acct.tsegay.common.App.main(App.java:23)
Caused by: org.hibernate.MappingException: Unknown entity: edu.acct.tsegay.model.User
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:580)
at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1365)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:100)
at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:74)
at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:793)
at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:771)
at org.springframework.orm.hibernate3.HibernateTemplate$25.doInHibernate(HibernateTemplate.java:843)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
... 6 more
You have to list your classes in your session factory configuration. You can have your entities auto-discovered if you are using EntityManager.
In order to use annotations with hibernate and spring, you have to use AnnotationSessionFactoryBean:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>edu.acct.tsegay.model.User</value>
</list>
</property>
....
</bean>
Also, it is rather strange that your User entity is a spring bean. You don't need that. Hibernate entities are supposed to be created with the new operator.
I've encountered the same problem and didn't find any good answer for this
What worked for me was to declare my entity class in the persistence.xml file:
<persistence ...>
<persistence-unit ...>
<class>com.company.maenad.core.model.News</class>
<class>com.company.maenad.core.model.AdExtraInfo</class>
</persistence-unit>
</persistence>
In addition to Bozho answer, if you are using spring + hibernate with annotation then in your session factory bean you can register your bean like below:
LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean.setDataSource(appContext.getBean(HikariDataSource.class));
localSessionFactoryBean.setAnnotatedClasses(
AppUser.class, Assignment.class
);