Spring和Hibernate集成

来源:互联网 发布:淘宝化妆品韩国女模特 编辑:程序博客网 时间:2024/05/22 10:39

第一次写博客,以前一直想写,由于自己文笔不好,一直没有尝试。前几天看了一篇文章,说写博文其实主要是给自己看,把所学所想留下来方便以后回顾,同时也给其他人些许帮助,于是下决心开始写。
这两天正在学spring,就把一些笔记放在这里,希望能给大家一些帮助。今天主要练习了spring和hibernate的继承,spring的其他知识以后有时间再来总结好了。
ps:纯属个人总结,为了以后看方便,可能会很啰嗦,各位切莫吐槽。

  1. 搭建环境
    (1)新建web工程
    (2)引入相关jar包
    spring相关jar包
    hibernate包有点多就不截图了
    注:aspectjrt.jar 和 aspectjweaver.jar是AOP相关包,原有spring2.5.6中的两个包貌似版本有问题,通过注解方式使用aop时没有效果,而通过xml配置文件使用aop时却有效果,搞了好久都不行,后来替换了这两个包才行。之后会上传到我的csdn上
    (3)程序结构
    这里写图片描述
    三个实体类:
    User.java
package com.turbo.entity;public class User {    private int id;    private String name;    private Role role;    private Department department;    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 Role getRole() {        return role;    }    public void setRole(Role role) {        this.role = role;    }    public Department getDepartment() {        return department;    }    public void setDepartment(Department department) {        this.department = department;    }    @Override    public String toString() {        return "User [id=" + id + ", name=" + name + ", role=" + role                + ", department=" + department + "]";    }}

User.hbm.xml
这里写图片描述

Role.java

package com.turbo.entity;public class Role {    private int rid;    private String rname;    public int getRid() {        return rid;    }    public void setRid(int rid) {        this.rid = rid;    }    public String getRname() {        return rname;    }    public void setRname(String rname) {        this.rname = rname;    }    @Override    public String toString() {        return "Role [rid=" + rid + ", rname=" + rname + "]";    }}

Department.java

package com.turbo.entity;public class Department {    private int did;    private String dname;    public int getDid() {        return did;    }    public void setDid(int did) {        this.did = did;    }    public String getDname() {        return dname;    }    public void setDname(String dname) {        this.dname = dname;    }    @Override    public String toString() {        return "Department [did=" + did + ", dname=" + dname + "]";    }}

Service层:
接口代码就不往出给了
UserServiceImpl.java

package com.turbo.service.impl;import javax.annotation.Resource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.turbo.dao.UserDao;import com.turbo.entity.User;import com.turbo.service.UserService;@Service("userService")public class UserServiceImpl implements UserService{    @Resource(name="userDao")    private UserDao userDao;    public void addUser(User user) {        // TODO Auto-generated method stub        System.out.println("调用service保存user");        userDao.addUser(user);    }    public void updateUser(User user) {        // TODO Auto-generated method stub        userDao.updateUser(user);    }    public User getUserById(int id) {        // TODO Auto-generated method stub        System.out.println("userService");        return userDao.getUserById(id);    }    public void deleteUserById(int id) {        // TODO Auto-generated method stub        userDao.deleteUserById(id);    }    public void setUserDao(UserDao userDao) {        this.userDao = userDao;    }}

Dao层:
同样不给接口代码了
UserDaoImpl.java

package com.turbo.dao.impl;import java.util.Iterator;import java.util.List;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import org.springframework.stereotype.Repository;import com.turbo.dao.UserDao;import com.turbo.entity.User;public class UserDaoImpl extends HibernateDaoSupport implements UserDao{    public void addUser(User user) {        // TODO Auto-generated method stub        this.getHibernateTemplate().save(user);    }    public void updateUser(User user) {        // TODO Auto-generated method stub        this.getHibernateTemplate().update(user);    }    public User getUserById(int id) {        // TODO Auto-generated method stub        String hql = "from User u where u.id="+id;        List users = this.getHibernateTemplate().find(hql);        User user = null;        if(!users.isEmpty()){            user = (User) users.get(0);        }        return user;    }    public void deleteUserById(int id) {        // TODO Auto-generated method stub        User user = getUserById(id);        this.getHibernateTemplate().delete(user);    }}

全都以User为例

  1. 配置hibernate
<hibernate-configuration>    <session-factory>        <property name="hibernate.connection.url">jdbc:mysql://localhost/spring_hibernate_test</property>        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="hibernate.connection.username">root</property>        <property name="hibernate.connection.password">111111</property>        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>        <property name="hibernate.show_sql">true</property>        <property name="hibernate.current_session_context_class">thread</property>        <!--         <property name="hibernate.current_session_context_class">jta</property>         -->                <mapping resource="com/turbo/entity/User.hbm.xml"/>        <mapping resource="com/turbo/entity/Role.hbm.xml"/>        <mapping resource="com/turbo/entity/Department.hbm.xml"/>    </session-factory></hibernate-configuration>
  1. 配置事务

关键配置spring

<?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:aop="http://www.springframework.org/schema/aop"         xmlns:tx="http://www.springframework.org/schema/tx"         xmlns:context="http://www.springframework.org/schema/context"         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"           >    <aop:aspectj-autoproxy proxy-target-class="true"/>    <context:annotation-config/>    <context:component-scan base-package="com.turbo"/>    <!-- 配置sessionFactory,将hibernate的配置文件引入,交给sessionFactory -->    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">        <property name="configLocation">            <value>classpath:hibernate.cfg.xml</value>        </property>    </bean>    <!-- 配置事务管理器 -->    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">        <property name="sessionFactory">            <ref bean="sessionFactory"/>        </property>    </bean>    <!-- 配置事务的传播特性 -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <tx:method name="add*" propagation="REQUIRED"/>            <tx:method name="delete*" propagation="REQUIRED"/>            <tx:method name="update*" propagation="REQUIRED"/>            <tx:method name="*" read-only="true"/>        </tx:attributes>    </tx:advice>    <!-- 配置切点 -->    <aop:config>        <aop:pointcut expression="bean (*Service)" id="serviceMethod"/>        <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>    </aop:config>    <bean id="departmentDao" class="com.turbo.dao.impl.DepartmentDaoImpl">        <property name="sessionFactory" ref="sessionFactory"></property>    </bean>    <bean id="roleDao" class="com.turbo.dao.impl.RoleDaoImpl">        <property name="sessionFactory" ref="sessionFactory"></property>    </bean>    <bean id="userDao" class="com.turbo.dao.impl.UserDaoImpl">        <property name="sessionFactory" ref="sessionFactory"></property>    </bean></beans>

4.写测试代码

package com.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.turbo.entity.Department;import com.turbo.entity.Role;import com.turbo.entity.User;import com.turbo.service.DepartmentService;import com.turbo.service.RoleService;import com.turbo.service.UserService;public class TestUser {//  @Test    public void testAdd(){        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-bean.xml");        UserService userService = (UserService) ctx.getBean("userService");        DepartmentService departmentService = (DepartmentService) ctx.getBean("departmentService");        RoleService roleService = (RoleService) ctx.getBean("roleService");        Role role = roleService.getRoleByRid(1);        Department department = departmentService.getDepartmentByDid(1);        System.out.println("role:"+role);        System.out.println(department);        User user = new User();        user.setDepartment(department);        user.setRole(role);        user.setName("张三");        userService.addUser(user);    }    @Test    public void testGet(){        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext-bean.xml");        UserService userService = (UserService) ctx.getBean("userService");        User user = userService.getUserById(1);        System.out.println(user);    }}

当然,在测试之前要先建立数据库,建立相应的表

0 0
原创粉丝点击