zoukankan      html  css  js  c++  java
  • java之spring之spring整合hibernate

    这篇讲下spring和hibernate的整合

    目录结构如下:

    1.新建java项目

    2.导入jar包

    antlr-2.7.7.jar

    aopalliance.jar

    aspectjweaver.jar

    commons-logging.jar

    dom4j-1.6.1.jar

    hibernate-commons-annotations-4.0.5.Final.jar

    hibernate-core-4.3.10.Final.jar

    hibernate-jpa-2.1-api-1.0.0.Final.jar

    jandex-1.1.0.Final.jar

    javassist-3.18.1-GA.jar

    jboss-logging-3.1.3.GA.jar

    jboss-logging-annotations-1.2.0.Beta1.jar

    jboss-transaction-api_1.2_spec-1.0.0.Final.jar

    mysql-connector-java-5.1.20-bin.jar

    spring-aop-4.1.6.RELEASE.jar

    spring-aspects-4.1.6.RELEASE.jar

    spring-beans-4.1.6.RELEASE.jar

    spring-context-4.1.6.RELEASE.jar

    spring-core-4.1.6.RELEASE.jar

    spring-expression-4.1.6.RELEASE.jar

    spring-jdbc-4.1.6.RELEASE.jar

    spring-orm-4.1.6.RELEASE.jar

    spring-tx-4.1.6.RELEASE.jar

    spring-web-4.1.6.RELEASE.jar

     3.编写vo类

    User.java

     1 package cn.vincent.vo;
     2 
     3 import java.io.Serializable;
     4 
     5 public class User implements Serializable{
     6     private int id;
     7     private String name;
     8     private int age;
     9     public int getId() {
    10         return id;
    11     }
    12     public void setId(int id) {
    13         this.id = id;
    14     }
    15     public String getName() {
    16         return name;
    17     }
    18     public void setName(String name) {
    19         this.name = name;
    20     }
    21     public int getAge() {
    22         return age;
    23     }
    24     public void setAge(int age) {
    25         this.age = age;
    26     }
    27     
    28 }
    View Code

    4.在src下,编写  hibernate.cfg.xml ,并且在cn.vincent.vo下编写vo类的映射文件 User.hbm.xml

    hibernate.cfg.xml

    <!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
        
    <hibernate-configuration>
        <session-factory>
            <!-- 数据库连接信息 -->
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <!-- 默认 localhost:3306 -->
            <property name="connection.url">jdbc:mysql:///test</property>
            <property name="connection.username">root</property>
            <property name="connection.password">root</property>
            
            <!-- 通用配置 -->
            <!-- 方言:hibernate要支持多种数据库,根据不同数据库生成对应的sql语句
                告诉hibernate使用的什么数据库,以便生成对应数据库的sql
             -->
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
            <property name="hbm2ddl.auto">update</property>
            <!-- 打印sql语句 -->
            <property name="show_sql">true</property>
            <!-- 格式化sql -->
            <property name="format_sql">true</property>
            <!-- 映射信息  注意映射文件存放的是文档路径 需要用/ -->
            <mapping resource="cn/vincent/vo/User.hbm.xml"/>
        </session-factory>
    </hibernate-configuration>

    User.hbm.xml

    <?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="cn.vincent.vo">
            <class name="User" table="t_user">
            <id name="id">
                <generator class="native"></generator>
            </id>
            <property name="name"/>
            <property name="age"/>
        </class>
    </hibernate-mapping>

    5.准备好工具包 cn.vincent.util 下的 HibernateUtil.java 文件

    HibernateUtil.java 

    package cn.vincent.util;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    
    public class HibernateUtil {
        private static Configuration cfg;
        private static ServiceRegistry registry;
        private static SessionFactory factory;
        private static ThreadLocal<Session> session;
        static{
            //初始化
            cfg = new Configuration().configure();
            registry = new StandardServiceRegistryBuilder()
                        .applySettings(cfg.getProperties())
                        .build();
            factory = cfg.buildSessionFactory(registry);
            session  =new ThreadLocal<>();
        }
        //获取连接
        public static Session getSession(){
            if(session.get()==null){
                session.set(factory.openSession());
            }
            return session.get();
        }
        //释放资源
        public static void close(){
            if(session.get()!=null){
                session.get().close();
                session.set(null);
            }
        }
    }

    6.编写 cn.vincent.dao 包下的 UserDao.java ,及cn.vincent.dao.impl下的 UserDaoImpl.java 文件

    UserDao.java

    package cn.vincent.dao;
    
    import java.util.List;
    
    import cn.vincent.vo.User;
    
    public interface UserDao {
    
        public List<User> findAll();
    }

    UserDaoImpl.java

    package cn.vincent.dao.impl;
    
    import java.util.List;
    
    import org.hibernate.Session;
    
    import cn.vincent.dao.UserDao;
    import cn.vincent.util.HibernateUtil;
    import cn.vincent.vo.User;
    
    public class UserDaoImpl implements UserDao{
    
        @Override
        public List<User> findAll() {
            Session session = HibernateUtil.getSession();
            return session.createQuery("from User").list();
        }
    
    }

    7.编写 cn.vincent.service 下的 UserService.java 和 cn.vincent.service.impl 下的 UserServiceImpl.java

    UserService.java

    package cn.vincent.service;
    import java.util.List;
    
    import cn.vincent.vo.User;
    
    
    public interface UserService {
        public List<User> findAll();
    }

    UserServiceImpl.java

    package cn.vincent.service.impl;
    
    import java.util.List;
    
    import cn.vincent.dao.UserDao;
    import cn.vincent.service.UserService;
    import cn.vincent.vo.User;
    
    public class UserServiceImpl implements UserService{
        private UserDao userDao;
        
        @Override
        public List<User> findAll() {
            return     userDao.findAll();
        }
        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }
    }

    8.编写spring配置文件:beans.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.xsd">
           
      <bean id="userDao" class="cn.vincent.dao.impl.UserDaoImpl"></bean>
      <bean id="userService" class="cn.vincent.service.impl.UserServiceImpl">
          <property name="userDao" ref="userDao"/>
      </bean>
      
      
    </beans>

    9.编写测试

    新建名为 test 的source folder,并且在cn.vincent.service 下添加 UserServiceTest.java文件

    package cn.vincent.service;
    
    import java.util.List;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cn.vincent.vo.User;
    
    public class UserServiceTest {
    
        @Test
        public void testFindAll(){
            ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
            UserService us = ac.getBean(UserService.class);
            List<User> list = us.findAll();
            System.out.println(list.size());
        }
    }

    10.运行测试,查看效果

     结束!

    补充:

    11.在 spring 整合 hibernate 时,可以将 hibernate 的所有配置都写入 spring 中,这样就可以不要 hibernate.cfg.xml 配置文件:

    beans.xml

    <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.xsd">
      <!-- 配置数据源:dbcp,c3p0,druid等 -->
      <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
          <property name="url" value="jdbc:mysql:///test"/>
          <property name="username" value="root"/>
          <property name="password" value="1111"/>
      </bean>
      <!-- sessionFactory对象由spring来创建 -->
      <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
          <property name="dataSource" ref="dataSource"/>
          <!-- 通用属性配置 -->
          <property name="hibernateProperties">
              <props>
                  <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                  <prop key="hibernate.show_sql">true</prop>
                  <prop key="hibernate.format_sql">true</prop>
              </props>
          </property>
          <!-- 配置映射文件 -->
          <property name="mappingLocations">
              <array>
                  <value>classpath:cn/sxt/vo/User.hbm.xml</value>
              </array>
          </property>
      </bean>
      <bean id="userDao" class="cn.sxt.dao.impl.UserDaoImpl">
          <property name="sessionFactory" ref="sessionFactory"/>
      </bean>
      <bean id="userService" class="cn.sxt.service.impl.UserServiceImpl">
          <property name="userDao" ref="userDao"/>
      </bean>
      
      
    </beans>

    12.spring的声明式事务

    <!-- 配置声明式事务 -->
      <!-- 配置事务管理器 -->
      <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
          <property name="sessionFactory" ref="sessionFactory"></property>
      </bean>
      <!-- 配置事务通知 -->
      <tx:advice id="txAdvice" transaction-manager="txManager">
          <tx:attributes>
              <!-- 表示以save开头的方法都需要事务      
              propagation  表示事务的传播特性 
              REQUIRED  查看当前是否有事务,如果有,使用当前事务,如果没有开启新事务
              -->
              <tx:method name="save*" propagation="REQUIRED"/>
              <tx:method name="update*" propagation="REQUIRED"/>
              <tx:method name="find*" read-only="true"/>
              <tx:method name="*" propagation="REQUIRED"/>
          </tx:attributes>
      </tx:advice>
      <!-- 配置事务aop  -->
        <aop:config>
            <!--expression  指明事务在哪里起作用
            第一个* 表示所有返回值 
            第二个* 表示所有类
            第三个* 表示类中的所有方法
            .. 表示所有参数
              -->
            <aop:pointcut expression="execution(* cn.sxt.service.impl.*.*(..))" id="pointcut"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
        </aop:config>  

     github地址:https://github.com/Vincent-yuan/spring_hibernate

  • 相关阅读:
    unity代码加密for Android,mono编译
    php __invoke 和 __autoload
    VC只运行一个程序实例
    VC单文档对话框添加托盘图标
    技术文档应该怎么写
    项目管理学习
    cannot download, /home/azhukov/go is a GOROOT, not a GOPATH
    Go语言学习
    appium键盘事件
    appium-doctor
  • 原文地址:https://www.cnblogs.com/Vincent-yuan/p/11257940.html
Copyright © 2011-2022 走看看