Spring与Hibernate整合

    xiaoxiao2021-04-13  32

    实例:http://pan.baidu.com/s/1eRFKEbg

    搭建环境:

    Spring与Hibernate整合 Spring 所需jar(大部分) Spring 基本 jar spring-beans-4.2.1.RELEASE.jar spring-context-4.2.1.RELEASE.jar spring-core-4.2.1.RELEASE.jar spring-expression-4.2.1.RELEASE.jar 日志 commons-logging-1.2.jar jdbc支持 spring-jdbc-4.2.1.RELEASE.jar 事务支持 spring-tx-4.2.1.RELEASE.jar Mysql连接驱动 mysql-connector-java-5.1.7-bin.jar 数据源c3p0/dbcp c3p0-0.9.1.2.jar commons-dbcp2-2.1.1.jar pool commons-pool2-2.4.2.jar aop联盟 com.springsource.org.aopalliance-1.0.0.jar Hibernate 基本 jar hibernate-c3p0-5.0.1.Final.jar hibernate-commons-annotations-5.0.0.Final.jar hibernate-core-5.0.1.Final.jar hibernate-entitymanager-5.0.1.Final.jar hibernate-jpa-2.1-api-1.0.0.Final.jar hibernate-jpamodelgen-5.0.1.Final.jar Aspectj 支持 com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar spring-aspects-4.2.1.RELEASE.jar 读写xml dom4j-1.6.1.ja 日志 slf4j-api-1.6.1.jar slf4j-log4j12-1.7.5.jar 整合jar spring-orm-4.2.1.RELEASE.jar

    实体:

    package com.hk.springdao.beans; public class Student { private Integer id; private String name; private int age; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; } }

    实体–映射

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.hk.springdao.beans"> <class name="Student"> <id name="id"> <generator class="native"></generator> </id> <property name="name"/> <property name="age"/> </class> </hibernate-mapping>

    业务接口

    package com.hk.springdao.service; import java.util.List; import com.hk.springdao.beans.Student; /** * * @author 浪丶荡 * */ public interface IStudentService { public void addStudent(Student stu); public void modifyStudent(Student stu); public void removeStudent(Student stu); public Student findStuByStuID(int stuID); public List<Student> findAllStudents(); }

    业务接口实现

    package com.hk.springdao.serviceimpl; import java.util.List; import com.hk.springdao.beans.Student; import com.hk.springdao.dao.IStudentDAO; import com.hk.springdao.service.IStudentService; public class StudentServiceImpl implements IStudentService { private IStudentDAO studentDao; public void setStudentDao(IStudentDAO studentDao) { this.studentDao = studentDao; } @Override public void addStudent(Student stu) { studentDao.insertStudent(stu); } @Override public void modifyStudent(Student stu) { studentDao.updateStudent(stu); } @Override public void removeStudent(Student stu) { studentDao.deleteStudent(stu); } @Override public Student findStuByStuID(int stuID) { return studentDao.selectStuByStuID(stuID); } @Override public List<Student> findAllStudents() { return studentDao.selectAllStudents(); } }

    dao

    package com.hk.springdao.dao; import java.util.List; import com.hk.springdao.beans.Student; public interface IStudentDAO { public void insertStudent(Student stu); public void updateStudent(Student stu); public void deleteStudent(Student stu); public Student selectStuByStuID(int stuID); public List<Student> selectAllStudents(); }

    dao实现

    package com.hk.springdao.daoimpl; import java.util.List; import org.hibernate.SessionFactory; import com.hk.springdao.beans.Student; import com.hk.springdao.dao.IStudentDAO; public class StudentDaoHbmImpl implements IStudentDAO{ private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void insertStudent(Student stu) { sessionFactory.getCurrentSession().save(stu); } @Override public void updateStudent(Student stu) { sessionFactory.getCurrentSession().update(stu); } @Override public void deleteStudent(Student stu) { sessionFactory.getCurrentSession().delete(stu); } @Override public Student selectStuByStuID(int stuID) { return sessionFactory.getCurrentSession().get(Student.class, stuID); } @Override public List<Student> selectAllStudents() { String hql = "from Student"; return sessionFactory.getCurrentSession().createQuery(hql ).list(); } }

    配置文件:

    <?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 注册数据源 (C3P0数据源) 从jdbc.properties中获取属性--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name= "driverClass" value="${jdbc.driver}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- 注册jdbc属性文件 方法二需要context约束 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 注册SessionFactory --> <bean id="mySessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 配置映射文件所在文件夹 --> <property name="mappingDirectoryLocations" value="com/hk/springdao/beans"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> </props> </property> </bean> <!-- 注册DAO --> <bean id="studentDAO" class="com.hk.springdao.daoimpl.StudentDaoHbmImpl"> <property name="sessionFactory" ref="mySessionFactory"></property> </bean> <!-- 注册Service --> <bean id="studentService" class="com.hk.springdao.serviceimpl.StudentServiceImpl"> <property name="studentDao" ref="studentDAO"></property> </bean> <!-- 注册事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"> <property name="sessionFactory" ref="mySessionFactory"></property> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" isolation="DEFAULT" propagation="REQUIRED"/> <tx:method name="remove*" isolation="DEFAULT" propagation="REQUIRED"/> <tx:method name="modify*" isolation="DEFAULT" propagation="REQUIRED"/> <tx:method name="find*" isolation="DEFAULT" propagation="REQUIRED" read-only="true"/> </tx:attributes> </tx:advice> <!-- aop配置 --> <aop:config> <aop:pointcut expression="execution(* *..service.*.*(..))" id="mypointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut"/> </aop:config> </beans>

    测试:

    package com.hk.springdao.test; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.hk.springdao.beans.Student; import com.hk.springdao.service.IStudentService; /** * * @author 浪丶荡 * */ public class MyTest { private IStudentService studentService; @Before public void before(){ String resouce = "applicationContext.xml"; ApplicationContext ac = new ClassPathXmlApplicationContext(resouce); studentService = (IStudentService) ac.getBean("studentService"); } @Test public void testAdd(){ Student stu = new Student("胡波",18); studentService.addStudent(stu ); } @Test public void testRemove(){ Student stu = new Student(); stu.setId(3); studentService.removeStudent(stu); } @Test public void testModify(){ Student stu = new Student(); stu.setId(1); stu.setAge(10); stu.setName("黑旋风"); studentService.modifyStudent(stu); } @Test public void testFindStudent(){ System.out.println(studentService.findStuByStuID(3)); System.out.println("-------------------------------"); System.out.println(studentService.findAllStudents()); } }

    数据库

    /* Navicat MySQL Data Transfer Source Server : localCnn Source Server Version : 60011 Source Host : localhost:3306 Source Database : test Target Server Type : MYSQL Target Server Version : 60011 File Encoding : 65001 Date: 2017-04-09 13:44:39 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `t_student` -- ---------------------------- DROP TABLE IF EXISTS `t_student`; CREATE TABLE `t_student` ( `t_id` int(5) NOT NULL AUTO_INCREMENT, `t_age` int(3) DEFAULT NULL, `t_name` varchar(20) DEFAULT NULL, PRIMARY KEY (`t_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_student -- ----------------------------
    转载请注明原文地址: https://ju.6miu.com/read-668620.html

    最新回复(0)