1、mybaits公共配置
<?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"/>
<!--别名,默认为类头个字母小写-->
<typeAliases>
<package name="com.fxf.pojo" />
</typeAliases>
<!--数据库配置,可以配置多个-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${pwd}"/>
</dataSource>
</environment>
</environments>
<!--引入mapper-->
<mappers>
<mapper resource="com/fxf/dao/UserMapper.xml"/>
</mappers>
</configuration>
1、mapper配置:
<?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.fxf.dao.UserDao">
<select id="getUserlist" resultType="user">
select * from user
</select>
<insert id="insertUser" parameterType="user">
insert into user(username,age,addr)values(#{username},#{age},#{addr})
</insert>
</mapper>
3、工具类
package com.fxf.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
public class MybaitsUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "mybaits-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (Exception e){
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
SqlSession session = sqlSessionFactory.openSession();
return session;
}
}
4、测试
import com.fxf.dao.UserDao;
import com.fxf.pojo.User;
import com.fxf.utils.MybaitsUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class MybaitsTest {
@Test
public void testDemo(){
SqlSession sqlSession = MybaitsUtil.getSqlSession();
System.out.println(sqlSession);
String username = "tom";
UserDao mapper = sqlSession.getMapper(UserDao.class);
for(int i=0;i<10;i++){
User user = new User();
user.setUsername(username+i);
user.setAge(15+i);
user.setAddr("zhongguo"+1);
mapper.insertUser(user);
}
List<User> userlist = mapper.getUserlist();
for (User user: userlist) {
System.out.println(user);
}
sqlSession.commit();
sqlSession.close();
}
}
5、整个结构: