Spring 整合 Hibernate + Mysql 的代码

阿超 发表于 2009-09-09 06:38 | 来源: | 阅读 330 次

开始用的是 MyEclipse 自带的 Derby 数据库,  发现单独的 Hibernate DAO 没有问题, 一整合 Spring 就插入不了数据, 甚至按照参考资料上的将 HibernateTransactionManager 的加进去也无济于事. 今天换成了 Mysql 就好了, 调试信息全打开也没看到什么出错, 不知原因, 甚是郁闷.

原因已经找到, 事务管理器没加对.具体解决方案请参考:

MyEclipse生成的Spring+Hibernate无法保存数据问题的解决方法

MyEclipse生成的Spring+Hibernate无法保存数据问题的解决方法2 – 用 CGLIB 来实现事务管理

可以新建一个 Java Project 然后添加 Hibernate 和 Spring 开发功能就能测试本文提到的代码了.

建表的 SQL:

CREATE TABLE `usertable` (
  `id` int(11) NOT NULL,
  `username` varchar(200) NOT NULL,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=GBK;

src/TestSpringHibernateDAO.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import entity.Usertable;

import spring_hibernate_dao.UsertableDAO;

public class TestSpringHibernateDAO {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
        "applicationContext.xml");

        UsertableDAO dao = UsertableDAO.getFromApplicationContext(ctx);

        Usertable user = new Usertable();
        user.setId(5);
        user.setUsername("5");
        user.setPassword("5");

        dao.save(user);
    }

}

src/entity/Usertable.java

package entity;

public class Usertable implements java.io.Serializable {

    // Fields

    private Integer id;

    private String username;

    private String password;

    // Constructors

    /** default constructor */
    public Usertable() {
    }

    /** full constructor */
    public Usertable(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    // Property accessors

    public Integer getId() {
        return this.id;
    }

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

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

src/entity/Usertable.hbm.xml

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping><class name="entity.Usertable" table="usertable" catalog="test"><id name="id" type="java.lang.Integer"><column name="id" /><generator class="assigned" /></id><property name="username" type="java.lang.String"><column name="username" length="200" not-null="true" /></property><property name="password" type="java.lang.String"><column name="password" length="20" not-null="true" /></property></class></hibernate-mapping>

src/spring_hibernate_dao/UsertableDAO.java

package spring_hibernate_dao;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import entity.Usertable;

/**
 * Data access object (DAO) for domain model class Usertable.
 *
 * @see spring_hibernate_dao.Usertable
 * @author MyEclipse Persistence Tools
 */

public class UsertableDAO extends HibernateDaoSupport {
    private static final Log log = LogFactory.getLog(UsertableDAO.class);

    // property constants
    public static final String USERNAME = "username";

    public static final String PASSWORD = "password";

    protected void initDao() {
        // do nothing
    }

    public void save(Usertable transientInstance) {
        log.debug("saving Usertable instance");
        try {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public void delete(Usertable persistentInstance) {
        log.debug("deleting Usertable instance");
        try {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Usertable findById(java.lang.Integer id) {
        log.debug("getting Usertable instance with id: " + id);
        try {
            Usertable instance = (Usertable) getHibernateTemplate().get(
                    "spring_hibernate.Usertable", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(Usertable instance) {
        log.debug("finding Usertable instance by example");
        try {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public List findByProperty(String propertyName, Object value) {
        log.debug("finding Usertable instance with property: " + propertyName
                + ", value: " + value);
        try {
            String queryString = "from Usertable as model where model."
                    + propertyName + "= ?";
            return getHibernateTemplate().find(queryString, value);
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List findByUsername(Object username) {
        return findByProperty(USERNAME, username);
    }

    public List findByPassword(Object password) {
        return findByProperty(PASSWORD, password);
    }

    public List findAll() {
        log.debug("finding all Usertable instances");
        try {
            String queryString = "from Usertable";
            return getHibernateTemplate().find(queryString);
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public Usertable merge(Usertable detachedInstance) {
        log.debug("merging Usertable instance");
        try {
            Usertable result = (Usertable) getHibernateTemplate().merge(
                    detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(Usertable instance) {
        log.debug("attaching dirty Usertable instance");
        try {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Usertable instance) {
        log.debug("attaching clean Usertable instance");
        try {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public static UsertableDAO getFromApplicationContext(ApplicationContext ctx) {
        return (UsertableDAO) ctx.getBean("UsertableDAO");
    }
}

src/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"

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

<bean id="sessionFactory"

        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="configLocation"

            value="file:src/hibernate.cfg.xml">

</property>

</bean>

<bean id="UsertableDAO" class="spring_hibernate_dao.UsertableDAO">

<property name="sessionFactory">

<ref bean="sessionFactory" />

</property>

</bean>

</beans>
src/hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
  <!DOCTYPE hibernate-configuration PUBLIC

          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="connection.username">root</property>

<property name="connection.url">

            jdbc:mysql://localhost/test

</property>

<property name="dialect">

            org.hibernate.dialect.MySQLDialect

</property>

<property name="myeclipse.connection.profile">

            mysql localhost

</property>

<property name="connection.driver_class">

            com.mysql.jdbc.Driver

</property>

<mapping resource="entity/Usertable.hbm.xml" />

</session-factory>

</hibernate-configuration>
喜欢Java豆技术站点的文章,那就通过 RSS Feed 功能订阅阅读吧!

我要评论

*

* 绝不会泄露



返回首页 | 关于我们 | 联系我们 | 广告合作 | 网站地图 | 友情链接 | 版权声明 | 模板设计