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

时间:2019-02-06 13:00:42

标签: java mysql spring hibernate java-ee

我是Spring的新手,正在尝试将Hibernate与Spring集成在一起。 我正在使用MySql数据库,并尝试使用saveOrUpdate()方法插入一条记录。

因此程序正在触发一个用于创建表的sql查询(应该如此)。

但是问题是,即使它正在触发“创建表”查询,也没有在数据库中创建表。 另外,如果该表是在数据库中手动创建的,然后尝试插入记录,则它什么也不做。

我尝试使用save()和persist()方法而不是saveOrUpdate(),但是我却一无所获。

这是主要课程。 已设置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);
}

这是bean类:     公职员工     {     私人int ID;     私有字符串名称;     私人int工资;     //获取器和设置器     }

这是包含所有配置的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>

这是DAO类:-

public class EmployeeDAO 
{
    HibernateTemplate template;

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

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

未在数据库中手动创建表时的输出:-

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...

手动创建表格时的输出:-

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=?**

仅执行此选择查询,而不插入一个。

1 个答案:

答案 0 :(得分:0)

通过添加一个使用注释来管理交易的

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

还为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);
    }
}