Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring-Hibernate:无法使用HibernateTemplate将对象数据保存到表中_Java_Spring_Hibernate - Fatal编程技术网

Java Spring-Hibernate:无法使用HibernateTemplate将对象数据保存到表中

Java Spring-Hibernate:无法使用HibernateTemplate将对象数据保存到表中,java,spring,hibernate,Java,Spring,Hibernate,我查看了整个stackoverflow,似乎找不到关于使用HibernateTemplate将创建的对象保存到数据库表(MySQL)的查询的答案。我正在使用Hibernate5和Spring5.0.7的最新迭代。我对Spring Hibernate非常陌生,以下是我迄今为止编写的代码: applicationContext.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springfra

我查看了整个stackoverflow,似乎找不到关于使用HibernateTemplate将创建的对象保存到数据库表(MySQL)的查询的答案。我正在使用Hibernate5和Spring5.0.7的最新迭代。我对Spring Hibernate非常陌生,以下是我迄今为止编写的代码:

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:context="http://www.springframework.org/schema/context"
    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">

    <bean id = "dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/edureka?useLegacyDatetimeCode=false&amp;serverTimezone=Europe/Amsterdam&amp;useSSL=false" />
        <property name="username" value="admin" />
        <property name="password" value="password" />
    </bean>

    <bean id= "mySessionFactory" class = "org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>mobilephone.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>

            </props>
        </property>

    </bean>

    <bean id = "dao" class = "co.module12.MobilePhoneDAO">
        <property name="sessionFactory" ref = "mySessionFactory"/>
    </bean>

</beans>
<!DOCTYPE hibernate-mapping PUBLIC
" - //Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping">

<hibernate-mapping>
    <class name = "co.module12.MobilePhone" table="mobiles">
        <id name="id">
            <generator class="increment"></generator>
        </id>
        <property name="manfacturer" />
        <property name="name" />
        <property name="price" />
        <property name="colour" />
    </class>
</hibernate-mapping>
package co.module12;

/**
 *
 * @author NetBeans
 */
public class MobilePhone {
    private String manfacturer;
    private String colour;
    private Double price;
    private String name;
    private Integer id;


    public MobilePhone() {

    }

    public String getManfacturer() {
        return manfacturer;
    }

    public void setManfacturer(String manfacturer) {
        this.manfacturer = manfacturer;
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }




}
package co.Module12;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;


/**
 *
 * @author NetBeans
 */
public class MobilePhoneDAO {
    HibernateTemplate template;
    SessionFactory factory;

    public void setSessionFactory(SessionFactory factory) {
       template = new HibernateTemplate(factory);
    }


    public void saveMobile(MobilePhone phone) {
        template.setCheckWriteOperations(false);
        template.save(phone);
        System.out.println(phone.getId());
        System.out.println(phone.getManfacturer());
        System.out.println(phone.getName());

    }

    public void updateMobile(MobilePhone phone) {
        template.update(phone);
    }

    public void deleteMobile(MobilePhone phone) {
        template.delete(phone);
    }

}
package co.Module12;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author NetBeans
 */
public class Module12MainClass {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        MobilePhoneDAO dao = (MobilePhoneDAO)context.getBean("dao");

        /*Create Mobile Phone One to Map to mySQL database*/
        MobilePhone samsungOne = new MobilePhone();
        samsungOne.setColour("black");
        samsungOne.setManfacturer("Samsung");
        samsungOne.setName("Galaxy S9+");
        samsungOne.setPrice(55158.25);
        samsungOne.setId(1001);
        dao.saveMobile(samsungOne);

        /*Create Mobile Phone Two to Map to mySQL database*/
        MobilePhone lgPhone = new MobilePhone();
        lgPhone.setColour("gray");
        lgPhone.setManfacturer("LG");
        lgPhone.setName("G7");
        lgPhone.setPrice(58782.25);
        lgPhone.setId(1002);
        dao.saveMobile(lgPhone);

    }

}
MobilePhoneDAO.java:

<?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"
    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">

    <bean id = "dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/edureka?useLegacyDatetimeCode=false&amp;serverTimezone=Europe/Amsterdam&amp;useSSL=false" />
        <property name="username" value="admin" />
        <property name="password" value="password" />
    </bean>

    <bean id= "mySessionFactory" class = "org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>mobilephone.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>

            </props>
        </property>

    </bean>

    <bean id = "dao" class = "co.module12.MobilePhoneDAO">
        <property name="sessionFactory" ref = "mySessionFactory"/>
    </bean>

</beans>
<!DOCTYPE hibernate-mapping PUBLIC
" - //Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping">

<hibernate-mapping>
    <class name = "co.module12.MobilePhone" table="mobiles">
        <id name="id">
            <generator class="increment"></generator>
        </id>
        <property name="manfacturer" />
        <property name="name" />
        <property name="price" />
        <property name="colour" />
    </class>
</hibernate-mapping>
package co.module12;

/**
 *
 * @author NetBeans
 */
public class MobilePhone {
    private String manfacturer;
    private String colour;
    private Double price;
    private String name;
    private Integer id;


    public MobilePhone() {

    }

    public String getManfacturer() {
        return manfacturer;
    }

    public void setManfacturer(String manfacturer) {
        this.manfacturer = manfacturer;
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }




}
package co.Module12;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;


/**
 *
 * @author NetBeans
 */
public class MobilePhoneDAO {
    HibernateTemplate template;
    SessionFactory factory;

    public void setSessionFactory(SessionFactory factory) {
       template = new HibernateTemplate(factory);
    }


    public void saveMobile(MobilePhone phone) {
        template.setCheckWriteOperations(false);
        template.save(phone);
        System.out.println(phone.getId());
        System.out.println(phone.getManfacturer());
        System.out.println(phone.getName());

    }

    public void updateMobile(MobilePhone phone) {
        template.update(phone);
    }

    public void deleteMobile(MobilePhone phone) {
        template.delete(phone);
    }

}
package co.Module12;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author NetBeans
 */
public class Module12MainClass {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        MobilePhoneDAO dao = (MobilePhoneDAO)context.getBean("dao");

        /*Create Mobile Phone One to Map to mySQL database*/
        MobilePhone samsungOne = new MobilePhone();
        samsungOne.setColour("black");
        samsungOne.setManfacturer("Samsung");
        samsungOne.setName("Galaxy S9+");
        samsungOne.setPrice(55158.25);
        samsungOne.setId(1001);
        dao.saveMobile(samsungOne);

        /*Create Mobile Phone Two to Map to mySQL database*/
        MobilePhone lgPhone = new MobilePhone();
        lgPhone.setColour("gray");
        lgPhone.setManfacturer("LG");
        lgPhone.setName("G7");
        lgPhone.setPrice(58782.25);
        lgPhone.setId(1002);
        dao.saveMobile(lgPhone);

    }

}
主文件:

<?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"
    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">

    <bean id = "dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/edureka?useLegacyDatetimeCode=false&amp;serverTimezone=Europe/Amsterdam&amp;useSSL=false" />
        <property name="username" value="admin" />
        <property name="password" value="password" />
    </bean>

    <bean id= "mySessionFactory" class = "org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mappingResources">
            <list>
                <value>mobilephone.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>

            </props>
        </property>

    </bean>

    <bean id = "dao" class = "co.module12.MobilePhoneDAO">
        <property name="sessionFactory" ref = "mySessionFactory"/>
    </bean>

</beans>
<!DOCTYPE hibernate-mapping PUBLIC
" - //Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping">

<hibernate-mapping>
    <class name = "co.module12.MobilePhone" table="mobiles">
        <id name="id">
            <generator class="increment"></generator>
        </id>
        <property name="manfacturer" />
        <property name="name" />
        <property name="price" />
        <property name="colour" />
    </class>
</hibernate-mapping>
package co.module12;

/**
 *
 * @author NetBeans
 */
public class MobilePhone {
    private String manfacturer;
    private String colour;
    private Double price;
    private String name;
    private Integer id;


    public MobilePhone() {

    }

    public String getManfacturer() {
        return manfacturer;
    }

    public void setManfacturer(String manfacturer) {
        this.manfacturer = manfacturer;
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }




}
package co.Module12;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;


/**
 *
 * @author NetBeans
 */
public class MobilePhoneDAO {
    HibernateTemplate template;
    SessionFactory factory;

    public void setSessionFactory(SessionFactory factory) {
       template = new HibernateTemplate(factory);
    }


    public void saveMobile(MobilePhone phone) {
        template.setCheckWriteOperations(false);
        template.save(phone);
        System.out.println(phone.getId());
        System.out.println(phone.getManfacturer());
        System.out.println(phone.getName());

    }

    public void updateMobile(MobilePhone phone) {
        template.update(phone);
    }

    public void deleteMobile(MobilePhone phone) {
        template.delete(phone);
    }

}
package co.Module12;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 *
 * @author NetBeans
 */
public class Module12MainClass {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        MobilePhoneDAO dao = (MobilePhoneDAO)context.getBean("dao");

        /*Create Mobile Phone One to Map to mySQL database*/
        MobilePhone samsungOne = new MobilePhone();
        samsungOne.setColour("black");
        samsungOne.setManfacturer("Samsung");
        samsungOne.setName("Galaxy S9+");
        samsungOne.setPrice(55158.25);
        samsungOne.setId(1001);
        dao.saveMobile(samsungOne);

        /*Create Mobile Phone Two to Map to mySQL database*/
        MobilePhone lgPhone = new MobilePhone();
        lgPhone.setColour("gray");
        lgPhone.setManfacturer("LG");
        lgPhone.setName("G7");
        lgPhone.setPrice(58782.25);
        lgPhone.setId(1002);
        dao.saveMobile(lgPhone);

    }

}
尝试向DAO方法添加Spring“@Transactional”()注释

可能发生的情况是(尽管我目前无法测试它,因为我目前没有适合您的数据库的JAR),尽管您的代码确实执行“save”方法(您可能会确定是否没有错误,并且可以在DAO中放置调试器),但Hibernate可能被设置为默认情况下执行所谓的“自动刷新”。这意味着Hibernate决定何时将记录刷新到数据库中,但由于没有事务,Hibernate不需要调用它。放置“@Transactional”注释将save调用绑定到一个Spring事务,在该事务中Hibernate会话也被绑定,这意味着当事务关闭时,会通知会话关闭,并且它应该刷新

更新:这是我使用H2数据源运行示例股票时遇到的错误:

BUG org.springframework.orm.hibernate5.HibernateTemplate - Could not retrieve pre-bound Hibernate session
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
    at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
    at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:699)
    at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:344)
    at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:326)
    at org.springframework.orm.hibernate5.HibernateTemplate.save(HibernateTemplate.java:640)
    at co.module12.MobilePhoneDAO.saveMobile(MobilePhoneDAO.java:23)
    at co.module12.Module12MainClass.main(Module12MainClass.java:23)
但是,需要对Spring上下文文件进行更新,以允许事务工作

<tx:annotation-driven transaction-manager="txManager"/><!-- a PlatformTransactionManager is still required -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- (this dependency is defined somewhere else) -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

这来自以下示例:

我把这段代码用于H2数据源,MySQL应该不会有太大的不同。然而,有三个警告:

  • 检查您的导入-它必须是Spring事务,而不是javax
  • 价格是货币性的,所以您应该映射到BigDecimal,而不是Double,因为精度很重要
  • 您应该依赖save()调用来生成您的ID-不要事先生成ID

  • 错误是什么?问题是没有通过HibernateTemplate将对象保存到表“mobiles”中。是否有任何输出/错误消息等?@Emre,没有。您使用的是基于XML的配置。我没有找到任何定义的
    transactionManager
    bean来使用
    @transaction
    您需要指定
    ,不幸的是,添加@Transactional注释并没有解决问题。(我将注释添加到所有DAO方法(保存、更新和删除))。在我能够使用数据源进行测试时进行了更新。@Al geBra这方面有什么进展吗?