SpringData,Spring与Hibernate整合小记

学习过程中国内对整合的代码文章少之又少,无奈每日对着英文博客和英文API翻译,在Spring+Hibernate+SpringData整合中其中一个异常曾经解决4天,希望和我一样的小鲜肉不要再碰头~文章中有不足的地方希望大家多多指正~谢谢~

请大家忽略package name

首先第一步需要准备相对应的jar包,jar包很关键,其中不少Exception都是源自jar缺少或者冲突,需要jar包的可以留言邮箱

第二部构建Domain实体

package priv.wxz.dao;

import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Created by wangxizhong on 16/11/1.
 */

@Entity(name = "user")
@DynamicInsert
@DynamicUpdate
public class User {
    @Id
    @Column
    private int id;
    @Column
    private String name;
    @Column
    private String password;
    @Column
    private String phone;
    @Column
    private String address;

    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 String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User(int id, String name, String phone, String address) {
        this.id = id;
        this.name = name;
        this.phone = phone;
        this.address = address;

    }

    public User() {
    }
}


第三步构建BaseDao,所有的Dao接口都需要实现这个此接口,此接口又继承了Repository相关接口以实现相对应的CRUD以及分页排序方法

package priv.wxz.data.domain;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.io.Serializable;
/**
 * Created by wangxizhong on 2016/11/4.
 * This is a framework of the underlying query method
 *Including the crud
 *This method must be inherited to achieve the following functions
 *Must be passed to ID, object
 *Database interaction Middleware
 */
@NoRepositoryBean
public interface BaseDao<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
    T save(T entity);

    Iterable<T> save(Iterable<? extends T> iterableEntity);

    T findOne(ID primaryKey);

    Iterable<T> findAll();

    long count();

    boolean exists(ID primaryKey);

    void delete(T entity);

    void delete(ID primaryKey);

    void delete(Iterable<? extends T> iterableEntity);

   // void deleteAll();

    Iterable<T> findAll(Sort sortInfo);

    Page<T> findAll(Pageable pageInfo);


}

第四步创建相对应的Dao接口以实现数据库操作

如果要使用update delete insert 需要添加事务注解  如果是复杂的例如多表连接需要使用@Query注解来实现自定义查询,并且在方法命名上尽量使用类似于findAll,并且有区别于spring规定命名

package priv.wxz.test;

import priv.wxz.dao.User;
import priv.wxz.data.domain.BaseDao;

/**
 * Created by wangxizhong on 2016/11/7.
 */
public interface UserDao extends BaseDao<User, Integer> {

    User findById(int id);
}

第五步  测试类

package priv.wxz.test;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import priv.wxz.dao.User;

/**
 * Created by wangxizhong on 2016/11/9.
 */
public class TestMain {
    private ApplicationContext context=null;
    private ServiceTest serviceTest=null;

    @Before
    public  void before(){
        context=new ClassPathXmlApplicationContext("applicationContext.xml");
        serviceTest=(ServiceTest)context.getBean(ServiceTest.class);
    }
    @Test
    public void testUser(){
        User user=serviceTest.showUser();
        System.out.println(user.getName()+"..."+user.getAddress()+"..."+user.getPhone());
    }
}

贴一下application配置文件

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
    <context:component-scan base-package="priv.wxz"/>
    <context:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" primary="true">
        <property name="username" value="{jdbc.username}"></property>
        <property name="password" value="{jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="packagesToScan" value="priv.wxz.dao"/>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.jdbc.batch_size">20</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.format_sql">false</prop>
                <prop key="hibernate.connection.useUnicode">true</prop>
                <prop key="hibernate.connection.characterEncoding">UTF-8</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache.xml</prop>
                <prop key="hibernate.hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory
                </prop>
                <prop key="hibernate.cache.use_query_cache">false</prop>
                <prop key="hibernate.connection.username">your db username</prop>
                <prop key="hibernate.connection.password">your db password</prop>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/db name?characterEncoding=utf-8"</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="dataSource" ref="dataSource"/>
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <jpa:repositories base-package="priv.wxz.test"
                      entity-manager-factory-ref="entityManagerFactory">
    </jpa:repositories>

</beans>

数据库配置文件db.properties
jdbc.username=yourdbname
jdbc.password=yourpassword
jdbc.url=jdbc:mysql://localhost:3306/dev
jdbc.driverClassName=com.mysql.jdbc.Driver


hibernate 缓存文件ehcache.xml

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<ehcache>

    <!-- Sets the path to the directory where cache .data files are created.

         If the path is a Java System Property it is replaced by
         its value in the running VM.

         The following properties are translated:
         user.home - User's home directory
         user.dir - User's current working directory
         java.io.tmpdir - Default temp file path -->
    <diskStore path="./target/tmp"/>


    <!--Default Cache configuration. These will applied to caches programmatically created through
        the CacheManager.

        The following attributes are required for defaultCache:

        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element beforeQuery it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element beforeQuery it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
    />

    <!--Predefined caches.  Add your cache configuration settings here.
        If you do not have a configuration for your cache a WARNING will be issued when the
        CacheManager starts

        The following attributes are required for defaultCache:

        name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
        maxInMemory       - Sets the maximum number of objects that will be created in memory
        eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
                            is never expired.
        timeToIdleSeconds - Sets the time to idle for an element beforeQuery it expires. Is only used
                            if the element is not eternal. Idle time is now - last accessed time
        timeToLiveSeconds - Sets the time to live for an element beforeQuery it expires. Is only used
                            if the element is not eternal. TTL is now - creation time
        overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
                            has reached the maxInMemory limit.

        -->

    <!-- Sample cache named sampleCache1
        This cache contains a maximum in memory of 10000 elements, and will expire
        an element if it is idle for more than 5 minutes and lives for more than
        10 minutes.

        If there are more than 10000 elements it will overflow to the
        disk cache, which in this configuration will go to wherever java.io.tmp is
        defined on your system. On a standard Linux system this will be /tmp"
        -->
    <cache name="sampleCache1"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           overflowToDisk="true"
    />

    <!-- Sample cache named sampleCache2
        This cache contains 1000 elements. Elements will always be held in memory.
        They are not expired. -->
    <cache name="sampleCache2"
           maxElementsInMemory="1000"
           eternal="true"
           timeToIdleSeconds="0"
           timeToLiveSeconds="0"
           overflowToDisk="false"
    /> -->

    <!-- Place configuration for your caches following -->

</ehcache>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值