项目使用的是mybatis,相比于hibernate,更轻量更简洁。但是有点不好的地方是无法根据entity生成(修改)表。特别是项目丢给测试的时候,开发和测试不是一个数据库。测试往往还要手动根据sql创建一次表。于是考虑在单元测试状态自动生成相关表结构。
方案很显然:spring-data-jpa+hibernate搞定。
配置maven依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
配置spring-data-jpa.xml
<!-- Jpa Entity Manager 配置 -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="packagesToScan" value="com.test.*.entities"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- 配置Spring Data的Hibernate接口 -->
<bean id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="MYSQL"/>
<property name="showSql" value="true"/>
</bean>
测试类
package com.test.service;
import com.alibaba.fastjson.JSON;
import com.test.dao.AccountDao;
import com.test.entities.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
/**
* spring-test with testng
* @author zacard
* @since 2015-09-10 12:53
*/
@ContextConfiguration(locations = {"classpath:spring-data-jpa.xml", "classpath:spring-services.xml"})
public class NormalServiceTest extends AbstractTestNGSpringContextTests {
@Autowired
private AccountDao accountDao;
//测试MBG生成的代码是否能正确运行和jap生成表
@Test
public void testMBG() {
Account account = accountDao.selectByPrimaryKey(1);
System.out.println("account json:"+ JSON.toJSONString(account));
}
}
输出正常,查看数据库表,也生成了。搞定~