Spring+Hibernate基于注解整合的单元测试

最近又试着又整合spring和hibernate,之间也出现过不少问题,献上单元测试例子

只有业务层和持久层


先贴上pom.xml 文件

1.

<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</groupId>
  <artifactId>mavenDemo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
   <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    
    <!-- Oracle Jdbc Driver -->
  <dependency>
    <groupId>com.github.noraui</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.2</version>
</dependency>
<!-- spring package -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.0.0.RELEASE</version>
    <scope>test</scope>
</dependency>

<!-- Hibernate package -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.10.Final</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.0.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.10.Final</version>
</dependency>
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
  </dependencies>
</project>


2.配置文件Hibernate的配置文件整合到Spring文件中了

<?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"
xmlns:orm="http://www.springframework.org/schema/orm"
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/aop 
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/orm
         http://www.springframework.org/schema/orm/spring-orm.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd ">
         
        <!-- 自动扫描包 -->
        <context:component-scan base-package="com.jiyx"/>
         <!-- 引入外部文件 -->
         <!-- 
            oracle.driver=oracle.jdbc.driver.OracleDriver
oracle.url=jdbc:oracle:thin:@localhost:1521:orcl
oracle.username=hr
oracle.password=hr
          -->
         <context:property-placeholder location="jdbc.properties"/>
         <!-- 配置数据源 -->
         <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
          <property name="driverClass" value="${oracle.driver}"/>
          <property name="jdbcUrl" value="${oracle.url}"/>
          <property name="user" value="${oracle.username}"/>
          <property name="password" value="${oracle.password}"/>
          <property name="maxPoolSize" value="40"></property>
<property name="minPoolSize" value="1"/>
<property name="initialPoolSize" value="1"/>
<property name="maxIdleTime" value="20"/>
<property name="maxStatements" value="1"/> 
         </bean>
         
         <!-- 配置sessionFactory -->   
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
 <!--这种方法是扫描包的,具体到包,两中写法-->
<property name="packagesToScan" value="com.jiyx.entity" />
<!-- <property name="packagesToScan">
<value>com.jiyx.entity</value>
</property> -->
<!-- 这种是如果实体和数据库映射是xml文件类型的话,使用下面的这种形式 -->
<!-- <property name="mappingResources">
           <list>
               <value>com/jiyx/mapping/User.hbm.xml</value>
            </list>
        </property> -->
<property name="hibernateProperties">
<props>
<prop key="dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>

</bean> 
<!-- 自动管理事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

</beans>

3.实体类

一开始无法扫描到实体类,网上查需要好几个包,后来看到实体类注解包有的已经整合到hibernate-commons-annotations中了

package com.jiyx.entity;


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


import org.hibernate.annotations.GenericGenerator;


@Entity
@Table(name="USERS")
public class User {
@Id
@GeneratedValue(generator="uuid")    
@GenericGenerator(name="uuid",strategy="uuid")
private String id;
private String name;
private String password;
private String idCard;

public User() {
super();
// TODO Auto-generated constructor stub
}


public String getId() {
return id;
}


public void setId(String id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getPassword() {
return password;
}


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


public String getIdCard() {
return idCard;
}


public void setIdCard(String idCard) {
this.idCard = idCard;
}

}


4.持久层

一开始持久层添加了事务,测试类里面也添加了事务,查询没有出现问题,插入的时候,控制台没有走到打印插入sql语句,事务就提前关闭了,整的我一顿好找- -‘’

package com.jiyx.dao.impl;


import java.util.List;


import javax.transaction.Transactional;


import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


import com.jiyx.dao.UserDao;
import com.jiyx.entity.User;


@Repository("userDao")
@Transactional
public class UserDaoImpl implements UserDao {

@Autowired
private SessionFactory sessionFactory;

@Override
public void save(User user) {
sessionFactory.getCurrentSession().save(user);
}


@SuppressWarnings("unchecked")
@Override
public List<User> query() {
return sessionFactory.getCurrentSession().createQuery("from User").list();
}


}



5.业务层



package com.jiyx.service.impl;


import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.jiyx.dao.UserDao;
import com.jiyx.entity.User;
import com.jiyx.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public void inserts(User user) {
userDao.save(user);
}
@Override
public List<User> queryAll() {
List<User> query = userDao.query();
return query;
}


}

6.单元测试类

package com.test;


import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.jiyx.entity.User;
import com.jiyx.service.UserService;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class springDemo {

@Autowired
private UserService userService;

/*@Autowired
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}*/


@Test
public  void addTest() {
System.out.println("1234");
User user = new User();
user.setIdCard("1101001");
user.setName("admin");
user.setPassword("password");
userService.inserts(user);
}
@Test
public  void queryTest() {
System.out.println("1234");
List<User> queryAll = userService.queryAll();
for(User user:queryAll) {
System.out.println(user);
}
}
}


7.工具类

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class HibernateUtils {
private static final SessionFactory sessionFactory = sessionFactory();
   private static SessionFactory sessionFactory() {
       try {
           return new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
       } catch (Throwable ex) {
           System.err.println("Initial SessionFactory creation failed." + ex);
           throw new ExceptionInInitializerError(ex);
       }
   }
   public static SessionFactory getSessionFactory() {
       return sessionFactory;
   }
   public static void shutdown() {
       // Close caches and connection pools
       getSessionFactory().close();
   }


}



控制台 打印信息

十一月 14, 2017 8:30:57 下午 org.springframework.test.context.support.AbstractTestContextBootstrapper getDefaultTestExecutionListenerClassNames
信息: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
十一月 14, 2017 8:30:57 下午 org.springframework.test.context.support.AbstractTestContextBootstrapper instantiateListeners
信息: Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
十一月 14, 2017 8:30:57 下午 org.springframework.test.context.support.AbstractTestContextBootstrapper getTestExecutionListeners
信息: Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@61dc03ce, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@50f8360d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2cb4c3ab, org.springframework.test.context.transaction.TransactionalTestExecutionListener@13c78c0b, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@12843fce]
十一月 14, 2017 8:30:58 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [applicationContext.xml]
十一月 14, 2017 8:30:58 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.GenericApplicationContext@28d25987: startup date [Tue Nov 14 20:30:58 CST 2017]; root of context hierarchy
十一月 14, 2017 8:30:59 下午 com.mchange.v2.log.MLog 
信息: MLog clients using java 1.4+ standard logging.
十一月 14, 2017 8:30:59 下午 com.mchange.v2.c3p0.C3P0Registry 
信息: Initializing c3p0-0.9.5.2 [built 08-December-2015 22:06:04 -0800; debug? true; trace: 10]
十一月 14, 2017 8:31:00 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.10.Final}
十一月 14, 2017 8:31:00 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
十一月 14, 2017 8:31:00 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
十一月 14, 2017 8:31:00 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource 
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, dataSourceName -> 1hge13d9r1fr0avuysn044|5e5d171f, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> oracle.jdbc.driver.OracleDriver, extensions -> {}, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, forceUseNamedDriverClass -> false, identityToken -> 1hge13d9r1fr0avuysn044|5e5d171f, idleConnectionTestPeriod -> 0, initialPoolSize -> 1, jdbcUrl -> jdbc:oracle:thin:@localhost:1521:orcl, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 20, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 40, maxStatements -> 1, maxStatementsPerConnection -> 0, minPoolSize -> 1, numHelperThreads -> 3, preferredTestQuery -> null, privilegeSpawnedThreads -> false, properties -> {user=******, password=******}, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, userOverrides -> {}, usesTraditionalReflectiveProxies -> false ]
十一月 14, 2017 8:31:01 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
十一月 14, 2017 8:31:02 下午 org.hibernate.id.UUIDHexGenerator <init>
WARN: HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF RFC 4122 compliant UUID values; consider using org.hibernate.id.UUIDGenerator instead
十一月 14, 2017 8:31:03 下午 org.springframework.orm.hibernate5.HibernateTransactionManager afterPropertiesSet
信息: Using DataSource [com.mchange.v2.c3p0.ComboPooledDataSource[ identityToken -> 1hge13d9r1fr0avuysn044|5e5d171f, dataSourceName -> 1hge13d9r1fr0avuysn044|5e5d171f ]] of Hibernate SessionFactory for HibernateTransactionManager
1234
十一月 14, 2017 8:31:03 下午 org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: 
    /* 
from
    User */ select
        user0_.id as id1_0_,
        user0_.idCard as idCard2_0_,
        user0_.name as name3_0_,
        user0_.password as password4_0_ 
    from
        USERS user0_
User [id=8a80808e5f914bee015f914c02230000, name=wangwu, password=8888888888, idCard=666]
User [id=402881895fba7ea1015fba7ea3120000, name=我管你是谁, password=8888888888, idCard=666]
User [id=402881895fab6dc5015fab6dc8890000, name=admin, password=password, idCard=1101001]
User [id=402881895fab6fcf015fab6fd2a00000, name=admin, password=password, idCard=1101001]
十一月 14, 2017 8:31:04 下午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.GenericApplicationContext@28d25987: startup date [Tue Nov 14 20:30:58 CST 2017]; root of context hierarchy


到此经过测试能够正常运行。

新手案例,如果有错误请指正谢谢!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Her 20

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值