Spring+hibernate整合的注解使用示例
Spring+hibernate整合的注解使用示例
jcc_codingBoy 发表于1年前
Spring+hibernate整合的注解使用示例
  • 发表于 1年前
  • 阅读 17
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

xml文件详情

spring-jdbc-config.xml

<?xml  version="1.0"  encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation=
               "http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-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/tx
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxActive" value="50"/>
        <property name="minIdle" value="10"/>
        <property name="maxIdle" value="20"/>
        <property name="maxWait" value="60000"/>
        <property name="initialSize" value="10"/>
        <property name="validationQuery" value="select 1 from dual" />
        <property name="testWhileIdle" value="true" />
    </bean>

    <context:component-scan base-package="com.jcc" />

    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:packagesToScan="com.jcc" p:dataSource-ref="dataSource"
          p:jpaVendorAdapter-ref="hibernateVendor" p:jpaPropertyMap-ref="jpaPropertyMap" />

    <util:map id="jpaPropertyMap">
        <entry key="hibernate.hbm2ddl.auto" value="none" />
        <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        <entry key="hibernate.max_fetch_depth" value="4" />
        <entry key="hibernate.cache.use_second_level_cache" value="false" />
        <entry key="hibernate.cache.use_query_cache" value="false" />
        <entry key="hibernate.cache.region.factory_class" value="org.hibernate.cache.ehcache.EhCacheRegionFactory" />
    </util:map>

    <bean id="hibernateVendor"
          class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
          p:database="MYSQL" p:showSql="false" p:generateDdl="true"
          p:databasePlatform="org.hibernate.dialect.MySQLDialect" />

    <!-- Transaction Config -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
          p:entityManagerFactory-ref="entityManagerFactory">
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager" />
    <aop:aspectj-autoproxy />
    <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
</beans>

 

spring-context.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"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xmlns:task="http://www.springframework.org/schema/task"

       xsi:schemaLocation="

            http://www.springframework.org/schema/beans

            http://www.springframework.org/schema/beans/spring-beans-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/aop

            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

            http://www.springframework.org/schema/task

            http://www.springframework.org/schema/task/spring-task-3.0.xsd">



    <context:component-scan base-package="com.jcc"/>

    <context:annotation-config />

    <aop:aspectj-autoproxy />

    <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>

    <bean id="configure" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">

        <property name="locations">

            <list>

                <value>classpath*:*.properties</value>

            </list>

        </property>

        <property name="ignoreUnresolvablePlaceholders" value="true" />

        <property name="fileEncoding" value="UTF-8"></property>

    </bean>





    <import resource="spring-jdbc-config.xml"/>

</beans>

 

system.properties

 

jdbc.username=root

jdbc.password=123456

jdbc.url=jdbc:mysql://192.168.3.100:3306/test?useUnicode=true&amp;characterEncoding=UTF-8

 

Java文件

BaseDao.java

package com.jcc.dao.base;



import com.jcc.dao.entity.BaseDomain;



import javax.persistence.EntityManager;

import java.util.List;



public interface IBaseDAO <T>{

    public EntityManager getEM();

    public Object save(Object t);

    public List<T> select(String sql, List<Object> params, Class<T> clazz);

}

 

BaseDAOImpl.java

package com.jcc.dao.base;



import com.jcc.dao.entity.BaseDomain;

import org.apache.poi.ss.formula.functions.T;

import org.springframework.stereotype.Repository;



import javax.persistence.EntityManager;

import javax.persistence.PersistenceContext;

import javax.persistence.Query;

import java.util.List;



@Repository

public class BaseDAOImpl implements IBaseDAO<T>{



    @PersistenceContext

    EntityManager entityManager;



    public EntityManager getEM() {

        return entityManager;

    }



    public Object  save(Object p) {

        entityManager.persist(p);

        return p;

    }



    public List<T> select(String sql, List<Object> params, Class<T> clazz) {

        Query query = entityManager.createNativeQuery(sql, clazz);

        if(params != null && params.size() > 0){

            for (int i = 0; i <params.size() ; i++) {

                query.setParameter(i+1,params.get(i));

            }

        }

        return query.getResultList();

    }

}

IBaseService.java

public interface IBaseService<T> {

    public Object save(Object o);



    public List<T> select(String sql,List<Object> params,Class<T> clazz);

}

 

BaseServiceImpl.java

@Service

public class BaseServiceImpl implements IBaseService<T> {

    @Resource

    IBaseDAO dao;



    @Transactional

    public Object save(Object p) {

        dao.save(p);

        return p;

    }



    public List<T> select(String sql,List<Object> params,Class<T> clazz) {

       return dao.select(sql,params,clazz);

    }

}

BaseDomain .java

@MappedSuperclass

public abstract class BaseDomain  implements Serializable{

    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    @Column(name = "id",length = 10)

    private Long id;



    public Long getId() {

        return id;

    }



    public void setId(Long id) {

        this.id = id;

    }

}

 

Person.java

@Entity

@Table(name = "t_persion")

public class Person extends  BaseDomain{

    @Column(name = "name",length = 50)

    private String name;

    @Column(name = "age",length = 10)

    private Integer age;

    @Column(name = "gender",length = 2)

    private Integer gender;

    @Column(name = "addressId",length = 10)

    private Long addressId;

   // create getter /setter method

  }

 

Address.java

@Entity

@Table(name = "t_address")

public class Address extends  BaseDomain{

    @Column(name = "address",length = 100)

    private String address;

    @Column(name = "num",length = 10)

    private Integer num;
//  getter /setter method

}   

 

PersonAddr.java

@Entity

public class PersonAddr extends BaseDomain implements Serializable {

    private String name;

    private Integer age;

    private String address;

    private String addressId;
 
//  getter /setter method



    @Override

    public String toString() {

        return "PersonAddr{ id="+getId() +

                ",name='" + name + '\'' +

                ", age=" + age +

                ", address='" + address + '\'' +

                "addressId="+addressId+'}';

    }

}

 

TestJDBC.java

public class TestJDBC {

    public static void main(String[] args){

        ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext("/spring-context.xml");

        IBaseService service = cxt.getBean(IBaseService.class);

        saveBean(service);

        selectBean(service);

    }



    private static void selectBean(IBaseService service) {

        List<Person> select = service.select("select d.* from t_persion d",null,Person.class);

        System.out.println("-----size:"+select.size());

        List<Object> params = new ArrayList<Object>();

        params.add(2);

        List<PersonAddr> select1 = service.select("select p.*,a.address,a.id as addressId " +  "from t_persion p,t_address a where p.addressId = a.id and a.id=?1",

                params, PersonAddr.class);

        for (Object o:select1) {

            System.out.println(o.toString());

        }

        System.out.println("-----size:"+select1.size());

    }



    private static void saveBean(IBaseService service) {

        Address address = new Address();

        address.setAddress("四川成都");

        address.setNum(22);

        Address addr = (Address)service.save(address);

        Person person = new Person();

        person.setName("Jason jmm");

        person.setAge(22);

        person.setGender(1);

        person.setAddressId(addr.getId());

        Person p = (Person)service.save(person);

    }

}

 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.jc.demo</groupId>

    <artifactId>test</artifactId>

    <version>1.0-SNAPSHOT</version>



    <properties>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <spring.version>4.1.6.RELEASE</spring.version>

        <jersey.version>1.12</jersey.version>

        <hibernate-entitymanager.version>4.3.8.Final</hibernate-entitymanager.version>

    </properties>

        <dependencies>

            <dependency>

                <groupId>junit</groupId>

                <artifactId>junit</artifactId>

                <version>4.9</version>

                <scope>test</scope>

            </dependency>

            <dependency>

                <groupId>com.google.guava</groupId>

                <artifactId>guava</artifactId>

                <version>20.0</version>

            </dependency>

            <dependency>

                <groupId>org.javassist</groupId>

                <artifactId>javassist</artifactId>

                <version>3.15.0-GA</version>

            </dependency>

            <dependency>

                <groupId>org.slf4j</groupId>

                <artifactId>slf4j-api</artifactId>

                <version>1.7.5</version>

            </dependency>

            <dependency>

                <groupId>org.slf4j</groupId>

                <artifactId>slf4j-log4j12</artifactId>

                <version>1.7.12</version>

            </dependency>

            <dependency>

                <groupId>jstl</groupId>

                <artifactId>jstl</artifactId>

                <version>1.2</version>

            </dependency>

            <dependency>

                <groupId>javax.servlet</groupId>

                <artifactId>servlet-api</artifactId>

                <version>2.4</version>

                <scope>provided</scope>

            </dependency>

            <dependency>

                <groupId>javax</groupId>

                <artifactId>javaee-api</artifactId>

                <version>7.0</version>

            </dependency>

            <dependency>

                <groupId>commons-lang</groupId>

                <artifactId>commons-lang</artifactId>

                <version>2.5</version>

            </dependency>

            <dependency>

                <groupId>commons-io</groupId>

                <artifactId>commons-io</artifactId>

                <version>2.4</version>

            </dependency>

            <dependency>

                <groupId>mysql</groupId>

                <artifactId>mysql-connector-java</artifactId>

                <version>5.1.18</version>

            </dependency>

            <dependency>

                <groupId>commons-dbcp</groupId>

                <artifactId>commons-dbcp</artifactId>

                <version>1.4</version>

                <exclusions>

                    <exclusion>

                        <groupId>xerces</groupId>

                        <artifactId>xerces</artifactId>

                    </exclusion>

                    <exclusion>

                        <groupId>xml-apis</groupId>

                        <artifactId>xml-apis</artifactId>

                    </exclusion>

                    <exclusion>

                        <groupId>commons-pool</groupId>

                        <artifactId>commons-pool</artifactId>

                    </exclusion>

                </exclusions>

            </dependency>

            <dependency>

                <groupId>commons-collections</groupId>

                <artifactId>commons-collections</artifactId>

                <version>3.2.1</version>

            </dependency>



            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-context</artifactId>

                <version>${spring.version}</version>

            </dependency>

            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-context-support</artifactId>

                <version>${spring.version}</version>

            </dependency>

            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-orm</artifactId>

                <version>${spring.version}</version>

            </dependency>

            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-core</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-tx</artifactId>

                <version>${spring.version}</version>

            </dependency>

            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-jdbc</artifactId>

                <version>${spring.version}</version>

            </dependency>



            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-webmvc</artifactId>

                <version>${spring.version}</version>

            </dependency>

            <dependency>

                <groupId>org.springframework</groupId>

                <artifactId>spring-test</artifactId>

                <version>${spring.version}</version>

            </dependency>



            <dependency>

                <groupId>org.aspectj</groupId>

                <artifactId>aspectjrt</artifactId>

                <version>1.6.6</version>

            </dependency>



            <dependency>

                <groupId>org.aspectj</groupId>

                <artifactId>aspectjweaver</artifactId>

                <version>1.6.6</version>

            </dependency>



            <dependency>

                <groupId>org.reflections</groupId>

                <artifactId>reflections</artifactId>

                <version>0.9.5</version>

                <exclusions>

                    <exclusion>

                        <groupId>org.slf4j</groupId>

                        <artifactId>slf4j-api</artifactId>

                    </exclusion>

                </exclusions>

            </dependency>



            <dependency>

                <groupId>cglib</groupId>

                <artifactId>cglib</artifactId>

                <version>2.2.2</version>

            </dependency>



            <dependency>

                <groupId>org.hibernate</groupId>

                <artifactId>hibernate-entitymanager</artifactId>

                <version>${hibernate-entitymanager.version}</version>

                <exclusions>

                    <exclusion>

                        <groupId>xml-apis</groupId>

                        <artifactId>xml-apis</artifactId>

                    </exclusion>

                </exclusions>

            </dependency>



            <dependency>

                <groupId>org.hibernate.javax.persistence</groupId>

                <artifactId>hibernate-jpa-2.1-api</artifactId>

                <version>1.0.0.Final</version>

            </dependency>



            <dependency>

                <groupId>com.alibaba</groupId>

                <artifactId>dubbo</artifactId>

                <version>2.5.3</version>

                <exclusions>

                    <exclusion>

                        <groupId>org.springframework</groupId>

                        <artifactId>spring</artifactId>

                    </exclusion>

                </exclusions>

            </dependency>



            <dependency>

                <groupId>com.alipay</groupId>

                <artifactId>api</artifactId>

                <version>1.0</version>

            </dependency>



            <dependency>

                <groupId>com.taobao.api</groupId>

                <artifactId>taobao-sms</artifactId>

                <version>1.0</version>

            </dependency>



            <dependency>

                <groupId>dom4j</groupId>

                <artifactId>dom4j</artifactId>

                <version>1.6.1</version>

            </dependency>

            <dependency>

                <groupId>jaxen</groupId>

                <artifactId>jaxen</artifactId>

                <version>1.1.6</version>

            </dependency>

            <dependency>

                <groupId>com.squareup.okhttp3</groupId>

                <artifactId>okhttp</artifactId>

                <version>3.3.1</version>

            </dependency>



            <dependency>

                <groupId>com.101tec</groupId>

                <artifactId>zkclient</artifactId>

                <version>0.3</version>

            </dependency>



            <dependency>

                <groupId>commons-pool</groupId>

                <artifactId>commons-pool</artifactId>

                <version>1.6</version>

            </dependency>



            <dependency>

                <groupId>redis.clients</groupId>

                <artifactId>jedis</artifactId>

                <version>2.8.0</version>

            </dependency>



            <dependency>

                <groupId>commons-logging</groupId>

                <artifactId>commons-logging</artifactId>

                <version>1.2</version>

            </dependency>



            <dependency>

                <groupId>com.alibaba</groupId>

                <artifactId>fastjson</artifactId>

                <version>1.1.41</version>

            </dependency>



            <dependency>

                <groupId>org.apache.httpcomponents</groupId>

                <artifactId>httpclient</artifactId>

                <version>4.3.6</version>

            </dependency>



            <dependency>

                <groupId>com.qiniu</groupId>

                <artifactId>qiniu-java-sdk</artifactId>

                <version>[7.0.0, 7.1.99]</version>

            </dependency>



            <dependency>

                <groupId>cn.jpush.api</groupId>

                <artifactId>jpush-client</artifactId>

                <version>3.2.9</version>

            </dependency>



            <dependency>

                <groupId>org.apache.poi</groupId>

                <artifactId>poi</artifactId>

                <version>3.8</version>

            </dependency>



            <dependency>

                <groupId>org.apache.poi</groupId>

                <artifactId>poi-ooxml</artifactId>

                <version>3.8</version>

            </dependency>

        </dependencies>

</project>

 

解释

使用EntityManager的createNativeSql(String sql,Class clazz)时,传入的Class要有Entity标记,同时有id主键;

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 0
博文 17
码字总数 13763
×
jcc_codingBoy
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: