本文只是简单使用mybatis框架
项目结构
依赖 pom.xml
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
实体类
package com.dyy.entity;
import lombok.Data;
/**
* @description:
* @author:
* @date: 2020/4/14 22:50
* @Version: 1.0
*/
@Data
public class Account {
private Integer accountId;
private Integer uId;
private Double amount;
}
数据访问接口类
package com.dyy.dao;
import com.dyy.entity.Account;
import java.util.List;
/**
* @description:
* @author:
* @date: 2020/4/14 22:49
* @Version: 1.0
*/
public interface IAccountDao {
/**
* 查询
* @return
*/
List<Account> findAll();
}
mapper映射文件
这需要注意 把mapper文件放在resources路径,如果放在src路径下的话,编译器是直接忽略该文件的,到时候启动项目会找不到mapper文件的(坑,主要是对idea工具不熟练)
<?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.dyy.dao.IAccountDao">
<select id="findAll" resultType="com.dyy.entity.Account">
select * from cw.account
</select>
</mapper>
核心配置文件
<?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>
<properties resource="db.properties"/>
<!--内置数据库连接池-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="jdbc"></transactionManager>
<dataSource type="pooled">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!--接口映射文件-->
<mappers>
<mapper resource="com/dyy/dao/IAccountDao.xml" />
</mappers>
</configuration>
测试类
package com.dyy;
import com.dyy.dao.IAccountDao;
import com.dyy.entity.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @description:
* @author:
* @date: 2020/4/14 23:17
* @Version: 1.0
*/
public class AppMybatis {
@Test
public void findAll() throws IOException{
InputStream in = null ;
SqlSession sqlSession = null ;
try{
in = Resources.getResourceAsStream("sqlMapConfig.xml");
sqlSession = new SqlSessionFactoryBuilder().build(in).openSession();
IAccountDao dao = sqlSession.getMapper(IAccountDao.class);
List<Account> all = dao.findAll();
System.out.println(all);
}finally {
if(sqlSession!= null){
sqlSession.close();
}
if(in != null){
in.close();
}
}
}
}
测试结果