Java Generate/Merge Files(3)DAO Layer of Mybatis

本文介绍使用MyBatis作为ORM工具的实践经验,包括配置文件、依赖引入、DAO层接口定义及单元测试等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java Generate/Merge Files(3)DAO Layer of Mybatis

I used Ibatis for years, I used hibernate for years as well. But my friend recommend mybatis to me sometime ago. So this time I tried to use Mybatis for my ORM tool.

pom.xml provide us the dependencies
<!-- myIbatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>

Database related XML configuration and properties
<!-- DATABASE -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>

<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- access -->
<property name="driverClass" value="${db.driver}" />
<property name="jdbcUrl" value="${db.url}" />
<property name="user" value="${db.user}" />
<property name="password" value="${db.password}" />
<!-- pool sizing -->
<property name="initialPoolSize" value="2" />
<property name="minPoolSize" value="2" />
<property name="maxPoolSize" value="20" />
<property name="acquireIncrement" value="3" />
<property name="maxStatements" value="0" />
<!-- retries -->
<property name="acquireRetryAttempts" value="30" />
<property name="acquireRetryDelay" value="1000" /> <!-- 1s -->
<property name="breakAfterAcquireFailure" value="false" />
<!-- refreshing connections -->
<property name="maxIdleTime" value="180" /> <!-- 3min -->
<property name="maxConnectionAge" value="10" /> <!-- 1h -->
<!-- timeouts and testing -->
<property name="checkoutTimeout" value="5000" /> <!-- 5s -->
<property name="idleConnectionTestPeriod" value="60" /> <!-- 60 -->
<property name="testConnectionOnCheckout" value="true" />
<property name="preferredTestQuery" value="SELECT 1" />
<property name="testConnectionOnCheckin" value="true" />
</bean>

<bean id="sourceDAO" class="org.mybatis.spring.mapper.MapperFactoryBean" >
<property name="mapperInterface" value="com.j2c.feeds2g.daos.SourceDAO" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="campaignDAO" class="org.mybatis.spring.mapper.MapperFactoryBean" >
<property name="mapperInterface" value="com.j2c.feeds2g.daos.CampaignDAO" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

mybatis-config.xml file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- namespace -->
<!--
<typeAliases>
<typeAlias alias="Source" type="com.j2c.feeds2g.models.Source" />
</typeAliases>
-->
<typeAliases>
<package name="com.j2c.feeds2g.models"/>
</typeAliases>
</configuration>


Disable other logging
com.mchange.v2.log.MLog=com.mchange.v2.log.FallbackMLog
com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL=WARNING

Configuration logging
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://jobs-stage.xxxxx.amazonaws.com:3306/jobs
db.user=xxxxxx
db.password=xxxxxxx

Actually, I only defined a XML mapping which will map our java objects to our database column. And I defined a java interface which will give use the handler to call the DAO layer.
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.j2c.feeds2g.daos.SourceDAO">
<resultMap type="com.j2c.feeds2g.models.Source" id="Source">
<id column="id" property="id" />
<result property="status" column="status"/>
</resultMap>

<select id="loadActiveSources" resultMap="Source">
SELECT id, status FROM job_sources
</select>

<!--
<insert id="insertUser" parameterType="User">
INSERT INTO users (firstName, lastName, email)
VALUES (#{firstName}, #{lastName}, #{email})
</insert>

<update id="updateUser" parameterType="User">
UPDATE users SET
firstName = #{firstName},
lastName = #{lastName},
email = #{email}
WHERE ID = #{id}
</update>
-->
</mapper>

package com.j2c.feeds2g.daos;

import java.util.List;

import com.j2c.feeds2g.models.Source;

public interface SourceDAO {

public List<Source> loadActiveSources();

}

Then we only need to unit tests the class and ENV
package com.j2c.feeds2g.daos;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.j2c.feeds2g.models.Source;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class SourceDAOTest {

@Autowired
@Qualifier("sourceDAO")
private SourceDAO sourceDAO;

@Test
public void dummy() {
Assert.assertTrue(true);
}

@Test
public void loadActiveSources(){
List<Source> results = sourceDAO.loadActiveSources();
Assert.assertNotNull(results);
}

}

References:
http://limingnihao.iteye.com/blog/781671

http://www.mybatis.org/spring/

https://blog.lanyonm.org/articles/2014/04/21/spring-4-mybatis-java-config.html

old sample
https://github.com/LTWangxi/spring-mb/tree/master/kdxr/src/main/resources/conf

c3p0 pool
https://gist.github.com/chrissom/2351568
alibaba pool
https://github.com/alibaba/druid
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值