I created a spring project (Spring 4.0.2). I present the required files:
spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employeeDAO" class="com.journaldev.spring.jdbc.dao.EmployeeDAOImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="employeeDAOJDBCTemplate" class="com.journaldev.spring.jdbc.dao.EmployeeDAOJDBCTemplateImpl">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost:1433;database=springdb"/>
<property name="username" value="lm" />
<property name="password" value="pp" />
</bean>
</beans>
Employee.java
#Entity
#Table(name="Employee")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#Column(name = "name")
private String name;
#Column(name = "role")
private String role;
// with getters, setters, default constructor, constructor using fields
}
EmployeeDAO.java
public interface EmployeeDAO
{
public List<Employee> getAll();
}
EmployeeDAOImpl.java
public class EmployeeDAOImpl implements EmployeeDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
List<Employee> empList = new ArrayList<Employee>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
con = dataSource.getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()){
Employee emp = new Employee();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setRole(rs.getString("role"));
empList.add(emp);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return empList;
}
}
EmployeeDAOJDBCTemplateImpl.java
public class EmployeeDAOJDBCTemplateImpl implements EmployeeDAO,Serializable {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<Employee> getAll() {
String query = "select id, name, role from Employee";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List<Employee> empList = new ArrayList<Employee>();
List<Map<String,Object>> empRows = jdbcTemplate.queryForList(query);
for(Map<String,Object> empRow : empRows){
Employee emp = new Employee();
emp.setId(Integer.parseInt(String.valueOf(empRow.get("id"))));
emp.setName(String.valueOf(empRow.get("name")));
emp.setRole(String.valueOf(empRow.get("role")));
empList.add(emp);
}
return empList;
}
}
The bean to call in order to extract the list of employees DataModelD.java :
#ManagedBean
#ViewScoped
public class DataModelD implements Serializable
{
private List<Employee> list;
private Employee employee;
private EmployeeDAO eDao;
#PostConstruct
public void init()
{
System.out.println("-----------------------------BEGIN List");
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
eDao = ctx.getBean("employeeDAOJDBCTemplate", EmployeeDAO.class);
employee = new Employee();
list = eDao.getAll();
System.out.println("---------------------------------------List size= " + list.size());
}
}
After running it(to display the list of employees), the following exception is displayed:
08:14:46,222 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "HiSpring.war"
08:15:29,271 INFO [stdout] (http-localhost-127.0.0.1-8080-1) -----------------------------BEGIN List
08:15:29,529 INFO [org.springframework.context.support.ClassPathXmlApplicationContext] (http-localhost-127.0.0.1-8080-1) Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#ca34ed: startup date [Wed Aug 17 08:15:29 GMT-08:00 2016]; root of context hierarchy
08:15:29,591 INFO [org.springframework.beans.factory.xml.XmlBeanDefinitionReader] (http-localhost-127.0.0.1-8080-1) Loading XML bean definitions from class path resource [spring.xml]
08:15:29,718 INFO [org.springframework.jdbc.datasource.DriverManagerDataSource] (http-localhost-127.0.0.1-8080-1) Loaded JDBC driver: com.microsoft.sqlserver.jdbc.SQLServerDriver
08:15:30,736 INFO [stdout] (http-localhost-127.0.0.1-8080-1) ---------------------------------------List size= 5
08:15:30,832 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (http-localhost-127.0.0.1-8080-1) Error Rendering View[/sarsoura/list.xhtml]: java.io.NotSerializableException: org.springframework.jdbc.datasource.DriverManagerDataSource
at java.io.ObjectOutputStream.writeObject0(Unknown Source) [rt.jar:1.7.0_55]
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source) [rt.jar:1.7.0_55]
Have you please any idea about this issue?.Any reply will be appreciated.
Related
When I run my createStudentDemo class I get the following error:
INFO: HHH000412: Hibernate Core {5.4.11.Final}
Exception in thread "main"
org.hibernate.internal.util.config.ConfigurationException: Could not
locate cfg.xml resource [hibernate.cfg.xml] at
org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:53) at
org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:215) at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
at org.hibernate.cfg.Configuration.configure(Configuration.java:244)
at
com.luv2code.hibernate.demo.CreateStudentDemo.main(CreateStudentDemo.java:15)
I don't understand why I have this error.
Here is the code of my createStudentDemo class:
package com.luv2code.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luv2code.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
// create session factory
SessionFactory factory= new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
//create a student object
System.out.println("creating new student object");
Student tempStudent = new Student("Paul", "Wall", "paul#luv2code.com");
//start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
//commit transaction
session.getTransaction().commit();
System.out.println("Done !");
}
finally {
factory.close();
}
}
}
and here is the code for my class student:
package com.luv2code.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
public Student() {
}
#Id
#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 Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
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 "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
and here is the code of my hibernate.cfg.xml file:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
and here is the location of my files:
Can someone help me please?
You hibernate.cfg.xml should be in classpath. Put it in src folder.
I work with Netbeans, Spring MVC and Oracle.
I want to use MappingSqlQuery to execute oracle sql. This is the java class which implements MappingSqlQuery
public class SelectAllDepartamentos extends MappingSqlQuery<Departamento> {
private static final String SQL_SELECT_DEPT =
"SELECT DEPT_NO, DNOMBRE, LOC FROM DEPT";
public SelectAllDepartamentos() {
}
public SelectAllDepartamentos(DataSource dataSource) {
super(dataSource,SQL_SELECT_DEPT);
}
#Override
protected Departamento mapRow(ResultSet rs, int i) throws SQLException {
Departamento dept = new Departamento();
dept.setNumero(rs.getInt("DEPT_NO"));
dept.setNombre(rs.getString("DNOMBRE"));
dept.setLocalidad(rs.getString("LOC"));
return dept;
}
}
The class which use SelectAllDepartamentos is . The method that I use is findAll
public class JdbcDepartamentoDao1 implements InitializingBean,DepartamentoDao{
private javax.sql.DataSource dataSource;
private JdbcTemplate jdbcTemplate;
private SelectAllDepartamentos selectdepartamentos;
public JdbcDepartamentoDao1() {
}
public JdbcDepartamentoDao1(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
}
public void setDataSource(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}
#Override
public List<Departamento> findAll() {
return this.selectdepartamentos.execute();
}
#Override
public List<Departamento> findByLocalidad(String localidad) {
return null;
}
#Override
public String findById(int iddepartamento) {
String nombre = jdbcTemplate.queryForObject("SELECT DNOMBRE from DEPT WHERE DEPT_NO = ?",
new Object[]{iddepartamento},String.class);
return nombre;
}
#Override
public void insertarDepartamento(Departamento departamento) {
}
#Override
public void modificarDepartamento(Departamento departamento) {
}
#Override
public void eliminarDepartamento(Departamento departamento) {
}
#Override
public void afterPropertiesSet() throws Exception {
if (dataSource == null){
throw new BeanCreationException("Debe establece el dataSource ContactDao");
}
}
}
My application-context.xml is
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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"
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">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="departamentoDao" class="dao.JdbcDepartamentoDao1">
<property name="dataSource" ref="dataSource"/>
</bean>
<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}" />
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
<bean id="selectAllDepartamentos" class="modelos.SelectAllDepartamentos">
<property name="dataSource" ref="dataSource"></property>
<constructor-arg type="DataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>
When I executed the method findAll
#Override
public List<Departamento> findAll() {
return this.selectdepartamentos.execute();
}
I get the error
Remove
/*public void setDataSource(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}*/
Change to arg
<bean id="departamentoDao" class="dao.JdbcDepartamentoDao1">
<constructor-arg ref="dataSource" />
</bean>
Update constructor
public JdbcDepartamentoDao1(javax.sql.DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.selectdepartamentos = new SelectAllDepartamentos();
}
I create a project with Hibernate 4.3.5 and JBoss 7.1.1.
I give you a screenshot about the composition of my project:
The jars on WEB-INF/lib are:
Bellow, are the rquired classes:
EntityDao.java
public class EntityDao implements EntityDaoInterface<Book, Integer>
{
private Session currentSession;
private Transaction currentTransaction;
public EntityDao() {
}
public Session openCurrentSession() {
currentSession = getSessionFactory().openSession();
return currentSession;
}
public Session openCurrentSessionwithTransaction() {
currentSession = getSessionFactory().openSession();
currentTransaction = currentSession.beginTransaction();
return currentSession;
}
public void closeCurrentSession() {
currentSession.close();
}
public void closeCurrentSessionwithTransaction() {
currentTransaction.commit();
currentSession.close();
}
private static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
public Session getCurrentSession() {
return currentSession;
}
public void setCurrentSession(Session currentSession) {
this.currentSession = currentSession;
}
public Transaction getCurrentTransaction() {
return currentTransaction;
}
public void setCurrentTransaction(Transaction currentTransaction) {
this.currentTransaction = currentTransaction;
}
public void persist(Person entity) {
getCurrentSession().save(entity);
}
public void update(Person entity) {
getCurrentSession().update(entity);
}
public void delete(Person entity) {
getCurrentSession().delete(entity);
}
#SuppressWarnings("unchecked")
public List<Person> findAllPersons() {
List<Person> persons = (List<Person>) getCurrentSession().createQuery("from Person").list();
return persons;
}
public Person findPersonById(Integer id) {
Person person = (Person) getCurrentSession().get(Person.class, id);
return person;
}
}
EntityDaoInterface.java
public interface EntityDaoInterface<T, Id extends Serializable>
{
public void persist(T entity);
public void update(T entity);
public T findById(Id id);
public void delete(T entity);
public List<T> findAll();
public void deleteAll();
}
EntityService.java
public class EntityService
{
private static EntityDao entityDao;
public EntityService() {
entityDao = new EntityDao();
}
public void persist(Person entity) {
entityDao.openCurrentSessionwithTransaction();
entityDao.persist(entity);
entityDao.closeCurrentSessionwithTransaction();
}
public void update(Person entity) {
entityDao.openCurrentSessionwithTransaction();
entityDao.update(entity);
entityDao.closeCurrentSessionwithTransaction();
}
public void remove(Person entity) {
entityDao.openCurrentSessionwithTransaction();
entityDao.delete(entity);
entityDao.closeCurrentSessionwithTransaction();
}
public Person findPersonById(int id) {
entityDao.openCurrentSession();
Person person = entityDao.findPersonById(id);
entityDao.closeCurrentSession();
return person;
}
public List<Person> findAllPersons() {
entityDao.openCurrentSession();
List<Person> persons = entityDao.findAllPersons();
entityDao.closeCurrentSession();
return persons;
}
public void deleteAll() {
entityDao.openCurrentSessionwithTransaction();
entityDao.deleteAll();
entityDao.closeCurrentSessionwithTransaction();
}
public EntityDao entityDao() {
return entityDao;
}
}
Person.java
#Entity
#Table(name = "person")
public class Person
{
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#Column(name = "age")
private int age;
#Column(name= "name")
String name;
public Person() {}
public Person(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
// With the methods: set, get, toString, hashCode, equals
}
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;database=ccc</property>
<property name="hibernate.connection.username">lm</property>
<property name="hibernate.connection.password">pp</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="com.esprit.entity.Book"/>
<mapping class="com.esprit.entity.Person"/>
</session-factory>
</hibernate-configuration>
DataModelBeanD.java
#SuppressWarnings("serial")
#ManagedBean
#ViewScoped
public class DataModelBeanD implements Serializable
{
private List<Person> list;
private Person person = new Person();
private boolean edit;
private EntityService entityService;
#PostConstruct
public void init()
{
entityService = new EntityService();
list = entityService.findAllPersons();
}
}
After running the project, the following error appears:
08:32:54,297 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS018559: Deployed "HelloJPAHibernate.war"
08:33:01,282 INFO [org.hibernate.annotations.common.Version] (http-localhost-127.0.0.1-8080-1) HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
08:33:01,290 INFO [org.hibernate.Version] (http-localhost-127.0.0.1-8080-1) HHH000412: Hibernate Core {4.3.5.Final}
08:33:01,293 INFO [org.hibernate.cfg.Environment] (http-localhost-127.0.0.1-8080-1) HHH000205: Loaded properties from resource hibernate.properties: {hibernate.connection.driver_class=org.h2.Driver, hibernate.service.allow_crawling=false, hibernate.dialect=org.hibernate.dialect.H2Dialect, hibernate.max_fetch_depth=5, hibernate.format_sql=true, hibernate.generate_statistics=true, hibernate.connection.username=sa, hibernate.connection.url=jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE, hibernate.bytecode.use_reflection_optimizer=false, hibernate.jdbc.batch_versioned_data=true, hibernate.connection.pool_size=5}
08:33:01,297 INFO [org.hibernate.cfg.Environment] (http-localhost-127.0.0.1-8080-1) HHH000021: Bytecode provider name : javassist
08:33:01,317 INFO [org.hibernate.cfg.Configuration] (http-localhost-127.0.0.1-8080-1) HHH000043: Configuring from resource: /hibernate.cfg.xml
08:33:01,318 INFO [org.hibernate.cfg.Configuration] (http-localhost-127.0.0.1-8080-1) HHH000040: Configuration resource: /hibernate.cfg.xml
08:33:01,366 INFO [org.hibernate.cfg.Configuration] (http-localhost-127.0.0.1-8080-1) HHH000041: Configured SessionFactory: null
08:33:01,453 WARN [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000402: Using Hibernate built-in connection pool (not for production use!)
08:33:01,455 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000401: using driver [com.microsoft.sqlserver.jdbc.SQLServerDriver] at URL [jdbc:sqlserver://localhost:1433;database=ccc]
08:33:01,457 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000046: Connection properties: {user=lm, password=****}
08:33:01,458 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000006: Autocommit mode: false
08:33:01,460 INFO [org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl] (http-localhost-127.0.0.1-8080-1) HHH000115: Hibernate connection pool size: 5 (min=1)
08:33:03,123 INFO [org.hibernate.dialect.Dialect] (http-localhost-127.0.0.1-8080-1) HHH000400: Using dialect: org.hibernate.dialect.SQLServer2008Dialect
08:33:03,255 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/HelloJPAHibernate].[Faces Servlet]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet Faces Servlet threw exception: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index;
at org.hibernate.cfg.annotations.EntityBinder.processComplementaryTableDefinitions(EntityBinder.java:936) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:824) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3788) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3742) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844) [hibernate-core-4.3.5.Final.jar:4.3.5.Final]
at com.esprit.dao.EntityDao.getSessionFactory(EntityDao.java:48) [classes:]
at com.esprit.dao.EntityDao.openCurrentSession(EntityDao.java:25) [classes:]
at com.esprit.dao.EntityService.findAllPersons(EntityService.java:86) [classes:]
at com.esprit.crud.dynamic.DataModelBeanD.init(DataModelBeanD.java:37) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.7.0_55]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.7.0_55]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.7.0_55]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.7.0_55]
I couldn't know what's missed, could you please help me solving this issue. Any proposition is appreciated.Thanks in advance.
I solved my problem by making Hibernate 4.2.21 instead of Hibernate 4.3.5. Then I re-create the method getSessionFactory() of the class EntityDao.java like bellow:
private static SessionFactory getSessionFactory()
{
if (sessionFactory == null) {
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
<property name="url" value="jdbc:sqlserver://localhost:1433/orderdb"/>
<property name="username" value="abc"/>
<property name="password" value="pqr"/>
</bean>
When i try to make connection using dataSource.getConnection()
Not allowing please help
*****Connection Code **********
public class DatabaseBeanH2 {
private DataSource dataSource;
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseBeanH2.class);
public DatabaseBeanH2(){}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void create() throws SQLException{
Statement sta = dataSource.getConnection().createStatement();
try {
sta.executeUpdate("CREATE TABLE orders ( id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, item VARCHAR(50), amount INT, description VARCHAR(300), processed BOOLEAN, consumed BOOLEAN);");
} catch (SQLException e) {
LOGGER.info("Table orders already exists");
}
}
public void destroy() throws SQLException {
dataSource.getConnection().close();
}
}
You have to inject the dataSource bean in your DatabaseBeanH2 in the camel/spring context, something like this:
<bean id="databaseBean" class="my.package.DatabaseBeanH2">
<property name="dataSource" ref="dataSource" />
</bean>
I am getting this error
menu_categories is not mapped [from menu_categories]
my hibernate call is
public List loadMenuCategories(SessionFactory sessionFactory){
List types = new ArrayList<MenuCategories>();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query query = session.createQuery("from menu_categories");
List result = query.list();
Iterator it = result.iterator();
while(it.hasNext()){
MenuCategories menuCategories = (MenuCategories)it.next();
types.add(menuCategories);
}
sessionFactory.close();
return types;
}
and my bean is
#Entity
#Table(appliesTo = "menu_categories")
public class MenuCategories extends BaseModel{
/**
*
*/
private static final long serialVersionUID = -4875305890823765933L;
}
package com.rizstien.myhotel.framework.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.apache.commons.lang.StringUtils;
public class BaseModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable=false)
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "description")
private String desc;
#Column(name = "is_active")
private boolean active;
#Column(name = "no_of_items")
private Integer noOfItems;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
if (!StringUtils.isEmpty(name)) {
this.name = name;
}
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
if (!StringUtils.isEmpty(desc)) {
this.desc = desc;
}
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Integer getNoOfItems() {
return noOfItems;
}
public void setNoOfItems(Integer noOfItems) {
this.noOfItems = noOfItems;
}
}
EDIT
this is my hibernate config file
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3311/myhotel</property>
<property name="hibernate.connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">5</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.rizstien.myhotel.menucategories.model.MenuCategories"/>
</session-factory>
The query you're executing is not SQL. It's HQL. HQL queries entities, not tables. It should thus be from MenuCategories. This entity, BTW, should be named MenuCategory, sicne one instance of it represent one category, and not several categories.
Read the documentation.
I had mentioned db name in annotation and it solved the problem
#Entity
#Table(name = "menu_categories", catalog="db_name")
public class MenuCategories extends BaseModel{
private static final long serialVersionUID = -4875305890823765933L;
}