简体   繁体   English

无法使用Spring和Hibernate集成自动创建表并插入记录

[英]Unable to create a table automatically and insert records using spring and hibernate integration

I am new to spring and trying to integrate hibernate with spring. 我是Spring的新手,正在尝试将Hibernate与Spring集成在一起。 I am using MySql database and trying to insert a record using saveOrUpdate() method. 我正在使用MySql数据库,并尝试使用saveOrUpdate()方法插入一条记录。

So the program is firing a sql query for creating table(as it should). 因此,该程序会触发一个用于创建表的sql查询(应如此)。

But the issue is, even though it is firing a query for 'create table', the table is not being created in database. 但是问题是,即使它正在触发“创建表”查询,也没有在数据库中创建表。 Also, if the table is created manually in the database and then try to insert the record, it does nothing. 另外,如果表是在数据库中手动创建的,然后尝试插入记录,则它不会执行任何操作。

I have tried using save() and persist() method instead of saveOrUpdate(), but it took me nowhere. 我尝试使用save()和persist()方法而不是saveOrUpdate(),但是我却一无所获。

This is the main class. 这是主要的类。 Values of the bean class(Employee) has been set in order to insert a record. 为了插入记录,已设置bean类(雇员)的值。

public static void main( String[] args )
{
    ApplicationContext context=new 
    ClassPathXmlApplicationContext("sphb.xml");
    EmployeeDAO edao=(EmployeeDAO) context.getBean("d");
    Employee e=new Employee();
    e.setId(1);
    e.setName("sourav");
    e.setSalary(100000);
    edao.saveEmployee(e);
}

This is the bean class:- public class Employee { private int id; 这是bean类:-公共类Employee {private int id; private String name; 私有字符串名称; private int salary; 私人int工资; //getters and setters } // getters和setters}

This is the xml file containing all the config. 这是包含所有配置的xml文件。

<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"  
xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">  
    <property name="driverClassName"  value="com.mysql.cj.jdbc.Driver"> 
    </property>  
    <property name="url" value="jdbc:mysql://localhost:3306/db"></property>  
    <property name="username" value="root"></property>  
    <property name="password" value="1234"></property>  
    </bean>

    <bean id="mysessionFactory" 
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> 
    <property name="dataSource" ref="dataSource"></property>  

    <property name="mappingResources">  
    <list>  
    <value>mapping.hbm.xml</value>  
    </list>  
    </property>  

    <property name="hibernateProperties">  
        <props>  
            <prop 
            key 
            ="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
            <prop key="hibernate.hbm2ddl.auto">update</prop>  
            <prop key="hibernate.show_sql">true</prop>  

        </props>  
    </property>  
    </bean>  

    <bean id="template" 
    class="org.springframework.orm.hibernate5.HibernateTemplate">  
    <property name="sessionFactory" ref="mysessionFactory"></property>  
    <property name="checkWriteOperations" value="false"></property>
    </bean>  

    <bean id="d" class="demo.sphbIntegrate.EmployeeDAO">  
    <property name="template" ref="template"></property>  
    </bean>

    </beans>

This is the DAO class:- 这是DAO类:

public class EmployeeDAO 
{
    HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public void saveEmployee(Employee e) 
    {
    template.saveOrUpdate(e);
    }
}

Output when table is not created manually in database:- 未在数据库中手动创建表时的输出:-

log4j:WARN No appenders could be found for logger 
(org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for 
more info.
**Hibernate: create table employee (id integer not null, name varchar(255), 
salary integer, primary key (id)) type=MyISAM
Hibernate: select employee_.id, employee_.name as name2_0_, 
employee_.salary as salary3_0_ from employee employee_ where employee_.id=?
Exception in thread "main" 
org.springframework.dao.InvalidDataAccessResourceUsageException: could not 
extract ResultSet; SQL [n/a]; nested exception is 
org.hibernate.exception.SQLGrammarException: could not extract ResultSet**
at org. springframework. orm. hibernate5. SessionFactoryUtils. 
convertHibernateAccessException (SessionFactoryUtils.java:230)
at org. springframework. orm. hibernate5. HibernateTemplate. doExecute 
(HibernateTemplate.java:387)
and 15 more...

Output when table is created manually:- 手动创建表时的输出:-

log4j:WARN No appenders could be found for logger 
(org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for 
more info.
**Hibernate: select employee_.id, employee_.name as name2_0_, 
employee_.salary as salary3_0_ from employee employee_ where employee_.id=?**

Just this select query is executed, not insert one. 仅执行此选择查询,而不插入一个查询。

Made it work by adding a which uses annotation for managing transactions 通过添加使用注释来管理交易的使其工作

  <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="mysessionFactory"></property> </bean> <tx:annotation-driven transaction-manager="txManager"/> 

Also added setter for sessionFactory and used annotation for transaction and gave the rights for write operation. 还为sessionFactory添加了setter,并为事务使用了注释,并赋予了写操作权限。

 public class EmployeeDAO { HibernateTemplate template; public void setTemplate(HibernateTemplate template) { this.template = template; } public void setSessionFactory(SessionFactory sessionFactory) { this.template=new HibernateTemplate(sessionFactory); } @Transactional(readOnly=false) public void saveEmployee(Employee e) { template.saveOrUpdate(e); } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM