码迷,mamicode.com
首页 > 编程语言 > 详细

使用Maven 整合Spring和hibernate 适合初级接触的学者

时间:2016-07-17 00:02:59      阅读:355      评论:0      收藏:0      [点我收藏+]

标签:


本文,主要介绍Spring 和 hibernate怎么去整合,废话就不多说了,如果不知道spring 和hibernate 是干嘛的,还请去问问度娘哈。下面开始一步一步搭建:

工具: Idea 

一、先搭建Spring

  1.新建一个maven项目:至于填写项目名称什么的就不一一介绍了

技术分享

这里我的idea没有自动生成test文件夹,需要大家自己建一下,之后的项目目录如下图所示:

技术分享

2.下面我贴出项目的Pom文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>shop</groupId>
    <artifactId>shop</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>shop Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <!--版本控制-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.2.4.RELEASE</spring.version>
        <hibernate.version>4.3.8.Final</hibernate.version>
        <struts2.version>2.3.20</struts2.version>
        <junit.version>3.8.1</junit.version>
    </properties>


    <dependencies>
        <!--单元测试配置-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!--sping 配置-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!--持久化配置  hibernate-->
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.8.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--mysql  数据库配置-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>4.3.5.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.9</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>shop</finalName>
    </build>
</project>
3、在resources里添加bean文件,IocTest.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="Date" class="java.util.Date"></bean>
</beans>
4.新建IocTest测试类,如:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath:IocTest.xml")  //通过注解的方式进行bean注入
public class IocTest {


    ///在这遇到个纠结很长时间的问题,才突然明白   spring  context
    // 容器是提前把bean管理的对象实例化在容器了。因此在使用的时候是不需要再实例化的,直接使用即可
    @Resource
    private Date date;//通过bean注入的对象是不需要实例化得

    private Date date1;//直接使用Date对象进行使用,需要进行实例化的
    @Test
    public void TestIco()
    {
        System.out.println(date);  //bean注入对象的输出
        System.out.println(date1);
        date1=new Date();
        System.out.println(date1);
        System.out.println(date1);
    }
}

输出结果如下:

Sat Jul 16 16:38:26 CST 2016
null
Sat Jul 16 16:38:26 CST 2016
Sat Jul 16 16:38:26 CST 2016

看到结果想必大家也明白了Spring容器的作用了

到这里Spring已经测试ok了


二、Spring 整合 hibernate,这里想说的是:spring是通过管理hibernate里的LocalSessionFactoryBean对象进行hibernate的Session管理的

上边的Pom.xml文件已经加入了hibernate了,这里就不单独介绍了

  1.使用Persistence 进行生成hibernate实体模型以及实体模型配置文件

  技术分享

  配置完Persitence后,配置DataBase 

技术分享

现在就可以进行生成实体模型和配置文件了:

技术分享

技术分享  

这样就生成了模型和配置文件,如下图:

技术分享

这里为了资源文件统一管理,我把UserEntity.hbm.xml放到resources里了

 3.首先新建bean文件,SpringContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
                http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

    <!-- 自动扫描与装配bean -->
    <context:component-scan base-package="com.fei.shop"></context:component-scan>
    <!-- 导入外部的properties文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 配置SessionFactory -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 指定hibernate的配置文件位置 -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>

        <!-- 配置c3p0数据库连接池 -->
        <property name="dataSource">
            <bean class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <!-- 数据连接信息 -->
                <property name="jdbcUrl" value="${jdbcUrl}"></property>
                <property name="driverClass" value="${driverClass}"></property>
                <property name="user" value="${userName}"></property>
                <propert name="password" value="${password}"></property>
            </bean>
        </property>
    </bean>

    <!-- 配置声明式事务管理(采用注解的方式) -->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>

4.新建jdbc.properties数据库配置文件

jdbcUrl     = jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
driverClass = com.mysql.jdbc.Driver
userName        = root
password    =root
5.新建TestDao层

package com.fei.shop.Dao;

import com.fei.shop.Model.UserEntity;

/**
 * Created by jing on 16/7/16.
 */
public interface TestDao {
    public void  save(UserEntity userEntity);
}
6.新建TestDaoIml层

package com.fei.shop.Dao;

import com.fei.shop.Model.UserEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by jing on 16/7/16.
 *  
 */
@Service    //一定要加Service注解,要不然启动会报错,找不到spring可管理的对象
@Transactional  //事务也必须配置,否则启动会报找不到事务的错误
public class TestDaoImpl implements TestDao {

    @Autowired  //bean对象装载注解注入
    private SessionFactory sessionFactory;
    //获取和当前线程绑定的Seesion

    private Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }

    public void save(UserEntity userEntity) {
        getSession().save(userEntity);
    }
}
7、Service层

package com.fei.shop.Service;

import com.fei.shop.Model.UserEntity;
import org.springframework.stereotype.Service;

/**
 * Created by jing on 16/7/11.
 */

public interface TestService {
    public void save(UserEntity userEntity); //用来测试Hibernate环境
}
ServiceImpl
package com.fei.shop.Service;

import com.fei.shop.Dao.TestDao;
import com.fei.shop.Model.UserEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Created by jing on 16/7/11.
 *
 *
 *
 *
 * */
@Service
public class TestImpl implements TestService {

    @Autowired
    private TestDao testDao;
    public void save(UserEntity userEntity) {
        testDao.save(userEntity);
    }
}

测试类:

package com.fei.shop.Action;

import com.fei.shop.Model.UserEntity;
import com.fei.shop.Service.TestImpl;
import com.fei.shop.Service.TestService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

/**
 * Created by jing on 16/7/11.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= "classpath:SpringContext.xml")
public class Test {

    @Autowired
    private TestService testService;
    @org.junit.Test
    public  void TestOrm()
    {

        UserEntity model=new UserEntity();
        model.setName("测试122");
        model.setSex(1);
        testService.save(model);

    }
}
到这就ok了,可以运行项目看数据是否保存成功了

注:在保存的时候一直遇到中文乱码的问题,数据库连接加了characterEncoding=utf-8也不管用,后来是发现,Mysql数据库在安装的时候默认的数据库编码方式导致的,如何修改数据库编码方式见:Mac 修改MYSQL 的默认编码格式 解决中文插入MySql里乱码




本人是一名.net开发,在自学java,有不对的地方大家尽情吐槽和指正哈











使用Maven 整合Spring和hibernate 适合初级接触的学者

标签:

原文地址:http://blog.csdn.net/yulinlin_fei/article/details/51924977

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!