Accessing Database in Multithreaded Environment in Java - java

I am trying to understand approaches to access a database in a Multi threaded environment.
I implemented a following spring example that queries object from database in multiple threads, it works fine but I am not to sure if this is the right way to do it.
database.xml file looks like this
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
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.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1522/orcl.168.0.106" />
<property name="username" value="system" />
<property name="password" value="admin" />
</bean>
<bean id="oracleJDBCTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref = "dataSource" />
</bean>
</beans>
UserDetails object
package com.dataReader;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
public class UserDetails implements RowMapper {
private String user_name;
private String password;
public String getUser_name() {
return user_name;
}
public void setUser_name(String username) {
this.user_name = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
UserDetails userDetails = new UserDetails();
userDetails.setUser_name(rs.getString("USER_NAME"));
userDetails.setPassword(rs.getString("PASSWORD"));
return userDetails;
}
}
Application class is as follows
package com.dataReader;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class Application {
static JdbcTemplate oracleJDBCTemplate;
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("database.xml");
oracleJDBCTemplate = (JdbcTemplate) context.getBean("oracleJDBCTemplate");
List<String> userList = new ArrayList<String>();
userList.add("system");
userList.add("user-1");
userList.add("user-2");
userList.add("user-10");
userList.add("user-12");
for(int i=0;i<userList.size();i++) {
RunnerData runnerData = new RunnerData(oracleJDBCTemplate,userList.get(i));
Thread thread = new Thread(runnerData);
thread.start();
}
}
}
class RunnerData implements Runnable{
private JdbcTemplate oracleJDBCTemplate;
private String username;
RunnerData(JdbcTemplate jdbcTemplate,String username){
this.oracleJDBCTemplate=jdbcTemplate;
this.username=username;
}
#Override
public void run() {
UserDetails userDetails= oracleJDBCTemplate.queryForObject("select user_name,password from User_details where user_name=?",
new Object[] {username},BeanPropertyRowMapper.newInstance(UserDetails.class));
System.out.println(userDetails.getUser_name()+" "+userDetails.getPassword());
}
}
Is that a right approach to access database in a multi-threaded environment especially where we have large number of threads accessing database?
Wouldn't JdbcTemplate lock the database while querying the object. What are your experience in designing & implementing such a scenario?
Thanks for your input on this.

You would use database connection pooling.
Using Oracle connection pooling from OJDBC library is one way, for example:
<bean id="datasource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="connectionCachingEnabled" value="true" />
<property name="url" value="jdbc:oracle:thin:#localhost:1522/orcl.168.0.106" />
<property name="username" value="system" />
<property name="password" value="admin" />
<property name="connectionCacheProperties">
<props merge="default">
<prop key="MinLimit>5</prop>
<prop key="MaxLimit">100</prop>
</props>
</property>
</bean>

Related

Error creating bean with name 'sassionFactory' defined in class path resource [resources/spring.xml]: Invocation of init method failed

Error Message
Please click for error message
I am looking for the solution of this error for the last 2 days but couldn't find. Please help me solve this. I also check other similar posts but unable to find a solution.
BEAN FILE
'''
package model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
private int id;
private String name;
private String email;
private String address;
public Student(int id, String name, String address, String email) {
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
geter/seter
'''
DAO INTERFACE
'''
package DAO;
import java.util.List;
import model.Student;
public interface StudentDAO {
public int save(Student st);
public boolean update(Student st);
public boolean delete(Student st);
public Student findByPK(int pk);
public List<Student> findAllUsingHQL(Student st);
public List<Student> findAllUsingCriteria(Student st);
}
'''
DAO IMPLEMENTATION
'''
package DAO;
import java.util.List;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.HibernateTemplate;
import model.Student;
public class StudentDAOImpl implements StudentDAO {
private HibernateTemplate ht;
public HibernateTemplate getHt() {
return ht;
}
public void setHt(HibernateTemplate ht) {
this.ht = ht;
}
public int save(Student st) {
return (Integer) ht.save(st);
}
public boolean update(Student st) {
ht.update(st);
return true;
}
public boolean delete(Student st) {
ht.delete(st);
return false;
}
public Student findByPK(int pk) {
Student std = ht.get(Student.class, pk);
return std;
}
public List<Student> findAllUsingHQL(Student st) {
#SuppressWarnings("unchecked")
List<Student> list = (List<Student>) ht.find("from Student");
return list;
}
public List<Student> findAllUsingCriteria(Student st) {
DetachedCriteria dc = DetachedCriteria.forClass(Student.class);
List<Student> list = (List<Student>) ht.findByCriteria(dc);
return list;
}
}
'''
main method*
Currently only looking for save operation.
'''
package test;
import org.springframework.beans.BeansException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import DAO.StudentDAOImpl;
import model.Student;
public class Client {
public static void main(String[] args) {
try {
ConfigurableApplicationContext ap = new ClassPathXmlApplicationContext("resources/spring.xml");
StudentDAOImpl dao = (StudentDAOImpl) ap.getBean("dao");
int l = dao.save(new Student(2, "ravi", "ravi.ymail.com", "goa"));
System.out.println(l);
ap.close();
} catch (BeansException e) {
e.printStackTrace();
}
}
}
'''
spring.xml
'''
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="bds" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
<property name="driverClassName"
value="org.postgresql.Driver" />
<property name="url"
value="jdbc:postgresql://localhost:5432/postgres" />
<property name="username" value="postgres" />
<property name="password" value="74484" />
<property name="maxActive" value="15" />
<property name="minIdle" value="5" />
<property name="maxWait" value="5000" />
</bean>
<!-- Create SessionFactory -->
<bean id="sassionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="bds" />
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hbm2ddl.auto">create</prop>
<prop key="show_sql">true</prop>
</props>
</property>
<property name="annotatedClasses">
<list>
<value>model.Student</value>
</list>
</property>
</bean>
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sassionFactory"></property>
</bean>
<bean id="dao" class="DAO.StudentDAOImpl">
<property name="ht" ref="hibernateTemplate"></property>
</bean>
</beans>
'''

Why "org.hibernate.hql.internal.ast.QuerySyntaxException: customer is not mapped [from customer]" error is coming

i am facing below error:
Type Exception Report
Message Request processing failed; nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: customer is not mapped [from customer]
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
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]
Entity 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:
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;
}
}
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>
There is a difference between the entity Customer and the relational table customer.
When you specify #Table(name="customer"), you ask your JPA implementation to use customer as table name which it is probably doing (check in your database).
When you specify createQuery("from customer", Customer.class), you ask your JPA implementation to create a JPQL query and customer is not a known entity because that's Customer or com.luv2code.springdemo.entity.Customer the entity.

No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined"}}

I'm having problem with my web-app, cannot deploy the project to WildFly.
Problem:
Caused by: java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookedRoomDao': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:222)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:87)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.start(UndertowDeploymentService.java:72)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1948) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1881) [jboss-msc-1.2.2.Final.jar:1.2.2.Final]
... 3 more
Here is 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:p="http://www.springframework.org/schema/p"
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.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>text_resources</value>
</list>
</property>
</bean>
<bean name="exceptionResolver" class="com.booking.common.HotelException" autowire="byName">
<property name="exceptionMappings">
<props>
<prop key="javax.servlet.jsp.JspException">exception</prop>
<prop key="javax.servlet.ServletException">exception</prop>
<prop key="java.lang.Exception">exception</prop>
<prop key="java.lang.Throwable">exception</prop>
<prop key="java.lang.RuntimeException">exception</prop>
<prop key="org.springframework.web.bind.ServletRequestBindingException">exception</prop>
</props>
</property>
</bean>
<bean id="mailSession" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:jboss/mail/Default"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/booking-war"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="true" autowire="default">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.booking.member.vo" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<context:component-scan base-package="com.booking.dao" />
<context:component-scan base-package="com.booking.member" />
<context:component-scan base-package="com.booking.service" />
</beans>
UserDaoImpl.java
package com.booking.dao.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.booking.dao.GenericDao;
import com.booking.dao.UserDao;
import com.booking.member.vo.AuthenticateUser;
#Repository("userDao")
public class UserDaoImpl implements UserDao{
#Autowired
GenericDao<AuthenticateUser,Long> genericDao;
#PersistenceContext
EntityManager entityManager;
#Override
public List<AuthenticateUser> userByName(String username) {
String queryStr = "SELECT u FROM AuthenticateUser u WHERE u.username= ? ";
return entityManager.createQuery(queryStr)
.setParameter(1,username).getResultList();
}
public AuthenticateUser create(AuthenticateUser t) {
return genericDao.create(t);
}
public AuthenticateUser read(Long id, Class<AuthenticateUser> c) {
return genericDao.read(id, c);
}
public AuthenticateUser update(AuthenticateUser t) {
return genericDao.update(t);
}
public void delete(AuthenticateUser t) {
genericDao.delete(t);
}
public List<AuthenticateUser> getAll(Class<AuthenticateUser> c) {
return genericDao.getAll(c);
}
}
GenericDaoImpl.java :
package com.booking.dao.impl;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.ejb.HibernateEntityManager;
import org.springframework.stereotype.Repository;
import com.booking.dao.GenericDao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
#Repository("genericDao")
public class GenericDaoImpl<T,PK extends Serializable> implements GenericDao<T, PK> {
protected Class<T> entityClass;
#PersistenceContext
protected EntityManager entityManager;
#Override
public T create(T t) {
this.entityManager.persist(t);
return t;
}
#Override
public T read(PK id,Class<T> c) {
return (T)this.entityManager.find(c, id);
}
#Override
public T update(T t) {
return this.entityManager.merge(t);
}
#Override
public void delete(T t) {
t = this.entityManager.merge(t);
this.entityManager.remove(t);
}
#Override
public List<T> getAll(Class<T> c){
return this.entityManager.createQuery("SELECT o FROM "+ c.getName() +" o").getResultList();
}
#Override
public List<T> getByFilter(T filter){
Session session = ((HibernateEntityManager)entityManager.unwrap(HibernateEntityManager.class)).getSession();
return session.createCriteria(filter.getClass()).add(Example.create(filter)).list();
}
}
BookedRoomDaoImpl.java :
package com.booking.dao.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.booking.common.CommonUtils;
import com.booking.dao.BookedRoomDao;
import com.booking.dao.GenericDao;
import com.booking.member.vo.BookedRoom;
import com.booking.member.vo.Booking;
import com.booking.member.vo.TimeRange;
import org.hibernate.criterion.Restrictions;
#Repository("bookedRoomDao")
public class BookedRoomDaoImpl implements BookedRoomDao{
#PersistenceContext
EntityManager entityManager;
#Autowired
GenericDao<TimeRange,Long> timeRangeDao;
#Override
public List<BookedRoom> getBookedRooms(long id,String date){
List<BookedRoom> list = new ArrayList<BookedRoom>();
List<TimeRange> timeRanges = timeRangeDao.getAll(TimeRange.class);
for(TimeRange timeRange:timeRanges){
BookedRoom bookedRoom = new BookedRoom();
Booking booking = null;
try{
booking = (Booking)entityManager.createNativeQuery("select * from Booking b where b.time_range = ?1 and b.room = ?2 and date_format(date_booked,'%Y-%m-%d') = ?3",Booking.class)
.setParameter(1,timeRange.getId())
.setParameter(2,id)
.setParameter(3,date)
.getSingleResult();
}catch (NoResultException e) {
}
if(booking!=null){
bookedRoom.setBookingId(booking.getBookingId());
bookedRoom.setDateBooked(booking.getDateBooked());
bookedRoom.setRoomName(booking.getRoom().getRoomName());
bookedRoom.setUserName(booking.getUserid().getUsername());
if(booking.getUserid().getId()==CommonUtils.getCurrentUserProfile().getUserId()){
bookedRoom.setOwner(true);
}
}
bookedRoom.setFromTime(timeRange.getFromTime());
bookedRoom.setToTime(timeRange.getToTime());
bookedRoom.setTrId(timeRange.getId());
list.add(bookedRoom);
}
return list;
}
#Override
public void deleteBooking(long bookingId,long userId){
entityManager.createNativeQuery("delete from booking where booking_id=?1 and userid=?2")
.setParameter(1, bookingId)
.setParameter(2,userId)
.executeUpdate();
}
#Override
public List getBookingByRoomId(long roomId){
return entityManager.createNativeQuery("select * from booking where room = ?1",Booking.class)
.setParameter(1, roomId)
.getResultList();
}
}
And hibernate.cfg.xml :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<validation-mode>NONE</validation-mode>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<!--value='create' to build a new database on each run; value='update' to modify an existing database; value='create-drop' means the same as 'create' but also drops tables when Hibernate closes; value='validate' makes no changes to the database-->
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.ImprovedNamingStrategy"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.ejb.cfgfile" value="/resources/hibernate/hibernate.cfg.xml"/>
</properties>
</persistence-unit>
</persistence>
You need to add entityManagerFactory like this:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="jpaProperties" ref="hibernatePropertiesBean"/>
<property name="packagesToScan">
<list>
<value>your.packages</value>
</list>
</property>
</bean>

Entity Manager NULL - Spring MVC JPA

In the following code the entityManager is null. What am I doing wrong? I need the entityManager to be injected automatically.
My Object Model:
#Entity
#Table(name = "jlocalidades", catalog = "7jogos")
public class Jlocalidades implements java.io.Serializable {
private Integer id;
private String nome;
private String descricao;
public Jlocalidades() {
}
public Jlocalidades(String nome, String descricao) {
this.nome = nome;
this.descricao = descricao;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "Id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "Nome", nullable = false, length = 200)
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
#Column(name = "Descricao", nullable = false, length = 200)
public String getDescricao() {
return this.descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
My Servlet
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<context:component-scan base-package="com.dtr.oas" />
<context:annotation-config/>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<!-- <resources mapping="/resources/**" location="/resources/" /> -->
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="mysqlDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.254.38:3306/7jogos" />
<property name="username" value="root" />
<property name="password" value="6+1Log.pt" />
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="mysqlDS"/>
<property name="persistenceProviderClass" value="org.hibernate.ejb.HibernatePersistence" />
</bean>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
My Persistence
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<!-- shouldn't be valid for java SE per specification, but it works for EclipseLink ... -->
<class>com.dtr.oas.model.Jlocalidades</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.254.38:3306/7jogos" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="6+1Log.pt" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.logging.level" value="SEVERE"/>
</properties>
</persistence-unit>
My controller that gives the ERROR
package com.dtr.oas.model;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.setelog.model.Jcelulas;
public class JlocalidadesHome implements IJlocalidadesHome {
private static final Log log = LogFactory.getLog(JlocalidadesHome.class);
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#PersistenceContext
private EntityManager entityManager;
public void persist(Jlocalidades transientInstance) {
log.debug("persisting Jlocalidades instance");
try {
EntityManager entityManager = Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void remove(Jlocalidades persistentInstance) {
log.debug("removing Jlocalidades instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}
public Jlocalidades merge(Jlocalidades detachedInstance) {
log.debug("merging Jlocalidades instance");
try {
Jlocalidades result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public Jlocalidades findById(Integer id) {
log.debug("getting Jlocalidades instance with id: " + id);
try {
Jlocalidades instance = entityManager.find(Jlocalidades.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
#Transactional
public List<Jlocalidades> All (){
log.debug("getting all Jlocalidades");
try {
List<Jlocalidades> instance = entityManager.createQuery("SELECT * FROM jlocalidades").getResultList();
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
You need #Controller on your controller class in order for spring to inject the entityManager into it. Since you want Spring to inject the EntityManager, do not do:
EntityManager entityManager = Persistence.createEntityManagerFactory("persistenceUnit").createEntityManager();
Generally, you will only call Persistence.createEntityManagerFactory() when you are running without a container.
Bootstrap class that is used to obtain an EntityManagerFactory in Java
SE environments.
You can do without persistence.xml by changing your EntityManager configuration:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="mysqlDS"/>
<property name="packagesToScan" value="YOUR.ENTITY.PKG" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generatedDdl" value="true" />
<property name="databasePlatform" value="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</bean>
</property>
</bean>
How is the controller instantiated ? Its need to be a spring managed bean.
You have classpath scanning xml defined in your conf file. But JlocalidadesHome is not annoated with Controller/Component.
By the way, use a controller to take inputs from a request, it should then call service classes ... and the service classes interact with the data layer classes

org.hibernate.hql.ast.QuerySyntaxException

org.hibernate.hql.ast.QuerySyntaxException:
users is not mapped [SELECT email, id
FROM users WHERE email='dsdd#dds.com'
AND password='asasas']
public ILogin authenticate(Login login) {
System.out.println(login);
System.out.println(login.getEmail());
String query = "SELECT email, id FROM users WHERE email='"
+ login.getEmail() + "' AND password='" + login.getPassword() + "'";
results = getHibernateTemplate().find(query);
System.out.println(results);
return null;
}
I have a Login Bean class... here it follows.
package
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Login {
public Login(){}
private Long id = null;
private String email;
private String password;
public Login(String email, String password)
{
this.email = email;
this.password = password;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
My application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" default-autowire="byName"
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/tx http://www.springframework.org/schema/tx/spring-tx-2.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="com.intermedix"/>
<context:annotation-config/>
<!-- Turn on #Autowired, #PostConstruct etc support -->
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.intermedix.domain.Login</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>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Even if it does not belong to your question:
Don't use Hibernate/JPA in this way (String concatination) !:
String query = "SELECT email, id FROM users AS u WHERE email='"+ login.getEmail() + "' AND password='" + login.getPassword() + "'";
Instead use HQL like prepared statements:
createQuery(
"SELECT l FROM login WHERE l.email=:email AND l.password=:password")
.setParameter("login",login.getEmail())
.setParameter("password",login.getPassword());
If you do it in "your style" you will have lot of fun with SQL Injections!
Next: read the hibernate reference about HQL, for me it looks like you are writing SQL instead of HQL.
SELECT email, id FROM users
What is "users"? There is nothing in your config or code called "users", so Hibernate has no idea what you're talking about.
Secondly, your Login class is not annotated with #Entity, so Hibernate is likely ignoring it.
So add the annotation, and most likely change your query to:
SELECT email, id FROM Login
Looks obvious to me : "users is not mapped..."
Either you didn't map the Users table, or you have it incorrectly configured.
#Entity
#Table(name="users")
public class Login {
You actually need to annotate Login class since you say (<property name="annotatedClasses">) that in application-context.xml for example like this.
#Column(name="password")
public String getPassword() {
return password;
}
List list = getHibernateTemplate().find("from Form3A where FAC_ID=?",FAC_ID);
HERE Form3A is name of class and config file is
<property name="annotatedClasses">
<list>
<value>org.fbis.models.Form3A</value>
</list>
</property>

Categories