Spring4 MVC 整合Hibernate5

    截止发帖时间(2016.01.22),Hibernate最新稳定版为5.0.7.Final,之前已经搭建好了 Spring4.2.4 的框架,这次我就直接基于之前的 Spring4.2.4 Demo,将最新的Hibernate整合进去,那就直接开始我们的Spring4.2.4+Hibernate5.0.7:

    本人的开发环境:
        Eclipse:Java EE IDE for Web Developers. Version: Mars.1 Release (4.5.1)
        JDK:jdk1.8.0_72
        Tomcat:8.0.26
        Mysql Server:5.5 

    一、jar包

    Hibernate5的jar包可以到 官网 下载:http://hibernate.org/orm/downloads/

    本次Spring4.2.4+Hibernate5.0.7所需的所有jar包(hibernate5是支持java8的,但也兼容java6,如果需要使用java8,添加hibernate_java8.jar即可,此处本人默认添加):

    jar
    下载好添加对应的jar包即可。

    二、配置Hibernate5

    1、applicationContext.xml

    其中,hibernateTemplate是Spring对hibernate的二次开发,使用起来很方便,个人建议使用若需更多了解,请转至:hibernateTemplate详解。配置的sessionFactory中,注入的时候,Spring返回的自动就是sessionFactory而不是LocalSessionFactoryBean,所以请不用担心。

    其他就不细说了,直接看代码:

  <!-- 开启IOC注解扫描 -->
    <context:component-scan base-package="com.anxpp.demo" />
    <!-- 开启MVC注解扫描 -->
    <mvc:annotation-driven />
    <!-- 以下为数据库和hibernate配置 -->
    <context:property-placeholder location="classpath:config/db.properties" />
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.mysql.driverClassName}" />
        <property name="url" value="${jdbc.mysql.url}" />
        <property name="username" value="${jdbc.mysql.username}" />
        <property name="password" value="${jdbc.mysql.password}" />
        <property name="maxActive" value="100"></property>
        <property name="minIdle" value="20"></property>
        <property name="maxWait" value="3000"></property>
        <property name="initialSize" value="30"></property>
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan">
            <list>
                <value>com.anxpp.demo.core.entity</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="hibernateTemplateMysql" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 定义事务管理器(声明式的事务) -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="interceptorPointCuts"
            expression="execution(* com.anxpp.demo.core.service..*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
    </aop:config>

    2、db.properties

    链接字符串加上createDatabaseIfNotExist=true后,如果数据库不存在,会自动创建。

    这是数据库的链接配置:

#mysql
jdbc.mysql.driverClassName=com.mysql.jdbc.Driver
jdbc.mysql.url=jdbc:mysql://127.0.0.1:3306/demo?createDatabaseIfNotExist=true
jdbc.mysql.username=root
jdbc.mysql.password=****

    三、代码编写

    下面的代码,我会尽量的精简(但完整),不占过多的篇幅。这里主要是dao层的编写。

    0、entity:

@Entity
@Table(name="DEMO_User")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private Date birthday;
    public User(){}
    public User(String name){
        this.name = name;
        birthday = new Date();
    }
    @Override
    public String toString() {
        return "{id:" + id + ",name:" + name + ",birthday:" + birthday + "}";
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

    1、dao层

    DemoDao:

public interface DemoDao {
    String test();
    void save(Object entity);
    Object findById(int id);
    void delete(Object entity);
    List<User> findAll();
}

    DemoDaoImpl
    (里面有用到了java8的一个新特性) 

@Repository
public class DemoDaoImpl implements DemoDao {
    @Autowired
    protected HibernateTemplate hibernateTemplateMysql;
    @Override
    public String test() {
        return "hello word!";
    }
    @Override
    public void save(Object entity) {
        hibernateTemplateMysql.save(entity);
    }
    @Override
    public void delete(Object entity) {
        hibernateTemplateMysql.delete(entity);
    }
    @SuppressWarnings("unchecked")
    @Override
    public List<User> findAll() {
        return (List<User>) hibernateTemplateMysql.find("from User");
    }
    @SuppressWarnings({ })
    @Override
    public Object findById(final int id) {
        //这个方法大可不必写这么麻烦,不过是为了演示hibernateTemplate的方便之处以及java8的一个新特性
        //这是java8之前的写法
//      return hibernateTemplateMysql.execute(new HibernateCallback() {
//          @Override
//          public Object doInHibernate(Session session) throws HibernateException {
//              String hql = "from User where id=?";
//              Query query = session.createQuery(hql);
//              query.setParameter(0, id);
//              return query.uniqueResult();
//          }
//      });
        //Lambda 表达式:请确保eclipse配置为JDK8才能这么写
        return hibernateTemplateMysql.execute((Session session)-> {
                String hql = "from User where id=?";
                Query query = session.createQuery(hql);
                query.setParameter(0, id);
                return query.uniqueResult();
        });
    }
}

     2、Service层

    service

public interface DemoService {
    String test();
    Object save(String name);
    boolean delete(int id);
    String findAll();
}

    serviceImpl

@Service
public class DemoServiceImpl implements DemoService {
    @Autowired
    DemoDao demoDao;
    @Override
    public String test() {
        return demoDao.test();
    }
    @Override
    public Object save(String name) {
        User user = new User(name);
        demoDao.save(user);
        return user;
    }
    @Override
    public boolean delete(int id) {
        User user = (User) demoDao.findById(id);
        if(user==null)
            return false;
        demoDao.delete(user);
        return true;
    }
    @Override
    public String findAll() {
        String r = "";
        for(User user:demoDao.findAll())
            r +=  user;
        return r;
    }
}

    3、controller:

@Controller
@RequestMapping("/")
public class DemoController {
    @Autowired
    DemoService demoService;
    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return demoService.test();
    }
    @RequestMapping("/")
    public String index(){
        return "index";
    }
    @RequestMapping(value="/save",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String save(String name){
        return "save保存成功:" + demoService.save(name).toString();
    }
    @RequestMapping(value="/del",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String delete(int id){
        return "del删除结果:" + demoService.delete(id);
    }
    @RequestMapping(value="/find",produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String findAll(){
        return "find查询结果:" + demoService.findAll();
    }
}

     四、运行测试

    调用save接口传入参数,然后查询数据,再删除数据,最后在查数据。

    1、运行项目:

    start

    2、调用save:

    save

    3、调用find:

    find

    4、调用delete:

    del

    5、调用find:

    FIND

     运行测试完成!

    五、下载

    Spring4 MVC 整合Hibernate5

    后续会持续更新其他框架最新稳定版本的集成并附上源码。