I have Spring MVC app with Hibernate. Earlier I had a class which works with session(database) for each entity and everything worked good. Now, I have abstract Dao class which is inherited by one class for each entity. When I want to insert new data in database, everything works good. But when I want to update the data, they reach the controller (I can print them in console) but Hibernate doesn't generate sql code for update. I turned on property of Hibernate to show sql and I saw that hibernate generated all sql queries except UPDATE. All methods in Abstract class work, except update method.
And one interesting thing is that I don't get any erors in console.
This is Intersection class
#Entity
#Table(name = "intersections")
public class Intersection implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "symbol")
private Integer symbol;
#Size(max = 256)
#Column(name = "title")
private String title;
#OneToMany(mappedBy = "intersection",cascade = CascadeType.ALL)
private List<Access> accessList;
Access class
#Entity
#Table(name = "accesses")
public class Access implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "symbol")
private Integer symbol;
#Size(max = 50)
#Column(name = "title")
private String title;
#JoinColumn(name = "intersection", referencedColumnName = "id")
#ManyToOne(cascade = CascadeType.ALL)
private Intersection intersection;
Abstract Class
public abstract class AbstractDao<T, I, A, P, ID extends Serializable> implements DaoInterface<T, I, A, P, ID>{
#Autowired
private SessionFactory sessionFactory;
private Class<T> classType;
public AbstractDao(){
ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
this.classType = (Class<T>)type.getActualTypeArguments()[0];
}
#Override
public void insert(T t) {
Session session = sessionFactory.getCurrentSession();
session.save(t);
}
#Override
public void update(T t) {
Session session = sessionFactory.getCurrentSession();
session.update(t);
}
#Override
public List<T> getAll() {
Session session = sessionFactory.getCurrentSession();
Criteria c = session.createCriteria(classType);
c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
c.addOrder(Order.asc("symbol"));
List<T> list = c.list();
return list;
}
#Override
public T getById(ID id) {
Session session = sessionFactory.getCurrentSession();
T a = (T)session.get(classType, id);
return a;
}
#Override
public List<T> getByIntersection(I i) {
Session session = sessionFactory.getCurrentSession();
Criteria c = session.createCriteria(classType);
c.add(Restrictions.eq("intersection", i));
c.addOrder(Order.asc("symbol"));
List<T> list = c.list();
return list;
}
#Override
public List<T> getByAccess(A a) {
Session session = sessionFactory.getCurrentSession();
Criteria c = session.createCriteria(classType);
c.add(Restrictions.eq("access", a));
c.addOrder(Order.asc("symbol"));
List<T> list = c.list();
return list;
}
#Override
public List<T> getByPole(P p) {
Session session = sessionFactory.getCurrentSession();
Criteria c = session.createCriteria(classType);
c.add(Restrictions.eq("pole", p));
c.addOrder(Order.asc("symbol"));
List<T> list = c.list();
return list;
}
AccessDao
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public class AccessDao extends AbstractDao<Access, Intersection, Access, Pole, Integer>{
}
Method in Controller
#RequestMapping(value = "/access", method = RequestMethod.POST)
public String accessUpdate(
#RequestParam Integer idInt,
#RequestParam Integer idAccess,
#RequestParam String symbol,
#RequestParam String title,
ModelMap model){
String naslov = "Ažuriranje prilaza";
model.addAttribute("naslov", naslov);
List<Intersection> intersections = intersectionDao.getAll();
model.addAttribute("intersections", intersections);
Intersection i = intersectionDao.getById(idInt);
Access a = (Access) accessDao.getById(idAccess);
a.setIntersection(i);
a.setSymbol(Integer.parseInt(symbol));
a.setTitle(title);
accessDao.update(a);
return "accessupdate";
}
EDIT: web.xml, spring configuration
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- Context -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/applicationContext.xml,
/WEB-INF/spring/database.xml,
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
<!-- Listeners -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Dispatcher Servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<max-file-size>10485760</max-file-size>
<max-request-size>20971520</max-request-size>
<file-size-threshold>5242880</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Filters -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>MultipartFilter</filter-name>
<filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/p http://www.springframework.org/schema/p/spring-p-4.0.xsd" >
<context:component-scan base-package="com.intersections.controller" />
<context:component-scan base-package="com.intersections.model" />
<context:component-scan base-package="com.intersections.dao" />
<mvc:annotation-driven />
<mvc:resources mapping="/assets/**" location="/assets/" />
<mvc:resources mapping="/pdf/**" location="/pdf/" />
</beans>
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.intersections.model.Intersection</value>
<value>com.intersections.model.Access</value>
<value>com.intersections.model.Pole</value>
<value>com.intersections.model.TrafficSignalController</value>
<value>com.intersections.model.Detector</value>
<value>com.intersections.model.SignalHead</value>
<value>com.intersections.model.PedestrianPushButton</value>
<value>com.intersections.model.PedestrianDisplay</value>
<value>com.intersections.model.User</value>
<value>com.intersections.model.Rank</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true" />
<tx:method name="find*" read-only="true" />
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<bean id="accessDao" class="com.intersections.dao.AccessDao" />
<bean id="detectorDao" class="com.intersections.dao.DetectorDao"/>
<bean id="intersectionDao" class="com.intersections.dao.IntersectionDao" />
<bean id="pedestrianDisplayDao" class="com.intersections.dao.PedestrianDisplayDao"/>
<bean id="pedestrianPushButtonDao" class="com.intersections.dao.PedestrianPushButtonDao"/>
<bean id="poleDao" class="com.intersections.dao.PoleDao"/>
<bean id="signalHeadDao" class="com.intersections.dao.SignalHeadDao"/>
<bean id="trafficSignalControllerDao" class="com.intersections.dao.TrafficSignalControllerDao"/>
<bean id="userDao" class="com.intersections.dao.UserDao" />
<bean id="exportExcel" class="com.intersections.service.ExportExcel" />
</beans>
spring-security.xml
<?xml version='1.0' encoding='UTF-8' ?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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-4.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd" >
<http pattern="/assets/**" security="none" />
<http auto-config="true">
<access-denied-handler error-page="/403"/>
<intercept-url pattern="/login" access="permitAll()"/>
<intercept-url pattern="/" access="permitAll()"/>
<intercept-url pattern="/pdf/**" access="hasRole('USER')"/>
<intercept-url pattern="/use/**" access="hasRole('USER')"/>
<intercept-url pattern="/insert/**" access="hasRole('FULLUSER')"/>
<intercept-url pattern="/update/**" access="hasRole('FULLUSER')"/>
<form-login login-page="/login"
default-target-url="/" />
<logout />
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDao" />
</authentication-manager>
</beans:beans>
You need to add following in your update method
session.flush();
Related
I am not able to auto-create table from maven spring mvc.
I was doing a spring mvc project using maven. By far i have got no errors but when i am trying to create table in my database using applicationconfig.xml it is not working. i have searched over the internet but my applicationconfig.xml seems fine to me. I have got no errors. Still the table is not created..
applicationconfig.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:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.milan.entities" /><!--scans model/entity/domain(name 3 but same) and registers-->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create-drop</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<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/inventorymanagement" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
</bean>
<tx:annotation-driven />
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
User Class
package com.milan.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class User implements Serializable{
#Id
#Column(name = "USER_ID")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
#Column(name = "USERNAME")
private String userName;
#Column(name = "PASSWORD")
private String password;
#Column(name = "IS_ENABLEd")
private boolean isEnabled;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
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 boolean isIsEnabled() {
return isEnabled;
}
public void setIsEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
}
There is no error while running the program however the table is not created automatically.
Put #Entity on your User class, if the table still not created try putting below annotations on the class:
#Entity
#Table(name = "`user`")
Could be happening because User is a reserve word in DB.
I am getting this error because of this my application is not able to create a bean for sessionFactory and bean for transactionManager.
nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.entity.Candidate"/>
Here I am sharing my code hope that gives better clarity.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="false">
<servlet>
<servlet-name>conceptedge</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
<listener class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/conceptedge-persistence.xml</param-value>
</context-param>
<servlet-mapping>
<servlet-name>conceptedge</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
sessionFactory bean:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="/WEB-INF/hibernate.cfg.xml"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/interview"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
in Dao layer, I am accessing the session as mentioned:
#Autowired
SessionFactory sessionFactory;
#Override
public List<Candidate> getCandidatesList() {
// TODO Auto-generated method stub
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Candidate.class);
return criteria.list();
}
entity class
package com.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.hibernate.annotations.GenericGenerator;
#Entity
public class Candidate {
private int number;
private String name;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#GenericGenerator(name = "system-uuid", strategy = "uuid")
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
servlet.xml:
<context:component-scan base-package="com" >
<context:include-filter type="regex" expression="com.*"/>
</context:component-scan>
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
You have to annotate your class with #Entity and #Table when using
<mapping class="com.entity.Candidate"/>
or else, you need to use sth like
<mapping resource="com/entity/Candidate.hbm.xml" />
and add the equivalent xml mapping file for your entity class.
also dont forget to initialize your sessionFactory with AnnationConfiguration class
new AnnotationConfiguration().configure().buildSessionFactory();
I try get data through jpa-hibernate, lazy join, but I got an error.
Here my stuff:
Table user_role
user_role_id username ROLE
2 petroff ROLE_ADMIN
Table user
id username password salt email profile phone repassword
6 petroff 12345 ${config.salt} petroff#еуые.com test petroff prifile "" 12345
Part class User
#Entity
#Table(name = "tbl_user")
#Repassword(pass = "password", repass = "repassword")
public class User {
#Id
#Column(name = "id")
private int id;
#NotNull
#Size(min = 2, max = 64)
#Column(name = "username")
private String username;
#NotNull
#Size(min = 2, max = 64)
#Column(name = "password")
private String password;
#Column(name = "salt")
private String salt;
#Email
#Column(name = "email")
private String email;
#NotEmpty
#Column(name = "profile")
private String profile;
private String repassword;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRole = new HashSet<UserRole>();
public Set<UserRole> getUserRole() {
return userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
Part class UserRole
#Entity
#Table(name = "user_roles")
public class UserRole {
#Id
#Column(name = "user_role_id")
private Integer userRoleId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "username", nullable = false)
private com.blog.blog.entity.User user;
#Column(name = "role", nullable = false, length = 45)
private String role;
//getter and setter methods
public Integer getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(Integer userRoleId) {
this.userRoleId = userRoleId;
}
call method
#Autowired
UserService us;
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String printHello(ModelMap model, HttpSession session) {
com.blog.blog.entity.User u = us.getByUserName("petroff");
Set<UserRole> userRoles = u.getUserRole();
return "hello";
}
Service
#Service
#Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#PersistenceContext
private EntityManager entityManager;
#Override
public User addUser(User u) {
User savedUser = userRepository.saveAndFlush(u);
return savedUser;
}
#Override
public void delete(Integer id) {
userRepository.delete(id);
}
#Override
public User editUser(User u) {
return userRepository.saveAndFlush(u);
}
#Override
public List<User> getAll() {
return userRepository.findAll();
}
#Override
public User getByUserName(String name) {
return userRepository.findByUserName(name);
}
}
config file
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/config.properties"/>
<context:component-scan base-package="com.blog.blog.service.impl"/>
<jpa:repositories base-package="com.blog.blog.repositories"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.drivers}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
<!-- spring based scanning for entity classes-->
<property name="packagesToScan" value="com.blog.blog.entity"/>
</bean>
<tx:annotation-driven/>
<bean id="userDetailsService"
class="com.blog.blog.service.impl.UserDetailsImpl">
</bean>
<import resource="spring-security.xml"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<bean id="sessionFactory" class="org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<aop:config>
<aop:pointcut id="userServicePointCut"
expression="execution(* com.blog.blog.service.impl.*Service.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="userServicePointCut"/>
</aop:config>
</beans>
I get User obj
com.blog.blog.entity.User u = us.getByUserName("petroff");
but when i call
Set<UserRole> userRoles = u.getUserRole();
i got an error:
Exception occurred in target VM: failed to lazily initialize a collection of role: com.blog.blog.entity.User.userRole, could not initialize proxy - no Session
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.blog.blog.entity.User.userRole, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:137)
at org.hibernate.collection.internal.PersistentSet.size(PersistentSet.java:156)
at com.blog.blog.controller.Main.printHello(Main.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at
You will need to initialize lazy collection in the service if you want to use it on the caller side. Try this
#Override
public User getByUserName(String name) {
User u = userRepository.findByUserName(name);
Hibernate.initialize(u.getUserRole());
return u;
}
There is plenty of discussions on this topic online, look it up if you want more background info on the subject.
I'm trying to learn hibernate and spring. The first thing I want to do is get some data from database using Hibernate.
What I am trying to do is getting all data from data base but I get null pointer exception.
Here is my code;
City.java (under com.hopyar.dao package)
#Entity
#Table(name = "Cities")
public class City implements Serializable{
private static final long serialVersionUID = 2637311781100429929L;
#Id
#GeneratedValue
#Column(name = "c_id")
int id;
#Column(name = "c_name")
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
CityService.java (under com.hopyar.service package)
#Service
public class CityService {
#PersistenceContext
private EntityManager em;
#Transactional
public List<City> getAllCities(){
List<City> result = em.createQuery("Select c From Cities c", City.class)
.getResultList(); // This is where I get the exeption.
System.out.println();
return result;
}
}
spring-context.xml(under webapp/WEB-INF)
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Enable annotation-based Spring MVC controllers (eg: #Controller annotation) -->
<mvc:annotation-driven/>
<!-- Classpath scanning of #Component, #Service, etc annotated class -->
<context:component-scan base-package="com.hopyar" />
<!-- Resolve view name into jsp file located on /WEB-INF -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- MySQL Datasource with Commons DBCP connection pooling -->
<bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/myproject"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</bean>
<!-- EntityManagerFactory -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- Transaction Manager -->
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Enable #Transactional annotation -->
<tx:annotation-driven/>
</beans>
Main.java(under com.hopyar.test package)
public class Main {
public static void main(String[] args) {
CityService service = new CityService();
List<City> cities = service.getAllCities();
System.out.println(cities.size());
}
}
You are instantiating service as new CityService(), which is wrong because you are bypassing Spring. This means your annotations are not proccessed, and em is null. You need to get your service from spring context.
CityService service = applicationContext.getBean("cityService");
You can try to use autowired annotation on CityService, and Spring will instantiate it.
I am trying to integrate Spring and Hibernate but when I run the code and submit my for then it throws this exception
org.springframework.dao.InvalidDataAccessResourceUsageException: could not insert: [com.xgrid.evaltask.Entities.User]; SQL [insert into User (UserName, passwd, ID) values (?, ?, ?)]; nested exception is org.hibernate.exception.SQLGrammarException: could not insert: [com.xgrid.evaltask.Entities.User] I found the reason on google but get stuckPlease guide me where I am wrong
Here is applicationcontext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
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">
<context:component-scan base-package="com.xgrid.evaltask"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
p:url="jdbc:sqlserver://DBURL:1433;databaseName=Test_DB"
p:username="sampleUser"
p:password="#123456asdfgh" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="com.xgrid.evaltask"
/>
<context:annotation-config />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
And here is hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<!-- Enable this to see the SQL statements in the logs-->
<property name="show_sql">true</property>
<!-- This will drop our existing database and re-create a new one.
Existing data will be deleted! -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
Here is my DAO class
#Repository("authorizeDao")
public class AuthorizeDaoImpl implements AuthorizeDao {
#Autowired
HiberAdd hiberAdd;
#Override
public boolean doAuthorize(Authentication authentication) {
System.out.println("Name: " + authentication.getUserName());
System.out.println("PW: " + authentication.getPassWord());
User user = new User();
user.setId(1212);
user.setName(authentication.getUserName());
user.setPasswd(authentication.getPassWord());
hiberAdd.add(user);
return true;
}
}
ANd this is my CRUD class
`#Service("hiberAdd")
#Transactional
public class HiberAdd {
#Resource(name="sessionFactory")
private SessionFactory sessionFactory;
public void add(User user) {
// Retrieve session from Hibernate
Session session = sessionFactory.getCurrentSession();
// Save
session.save(user);
System.out.println("Saved ......................... ");
}
}`
This is my Entity Class
`#Entity
#Table(name="User")
public class User implements Serializable{
#Id
#Column(name="ID")
private Integer id;
#Column(name="UserName")
private String name;
#Column(name="passwd")
private String passwd;
//getters setters
USER is a reserved keyword of your database. Use another name for your table.