mybatis 入门
官文文档
http://www.mybatis.org/mybatis-3/zh/configuration.html#typeAliases
mybatis 配置文件
- 全局配置文件 引入 dtd 约束
<?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">
- 接口映射文件 dtd 约束
<?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">
标签详解(只讲标签功能, 具体使用 查看官方api)
全局配置文件
configuration >> 跟标签
- properties >> 引入外部文件
- settings >>
|- 可以开启驼峰命名, 默认是关闭 - typeAliases >> 别名处理器
|- 给java类型取别名(不区分大小写) - typeHandlers >> 类型处理器
- plugins >> 插件
|- 拦截 Executor/ParameterHandler/ResultSetHandler/StatementHandler 四个对象的方法 - environments >> 环境配置
|-environments 可以配置多个环境, default 指定使用哪种环境 - databaseIdProvider >> 支持多数据库厂商
- mappers >> 注册sql 映射
入门案例
注意: mybatis 默认 手动提交事务,自动 提交需要 openSession(true);
- 全局配置
<?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="DataSource.properties"/>
<typeAliases>
<package name="com.entity"/>
</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="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 映射sql的三种配置方式 -->
<!-- 通过类名 -->
<mapper class="com.dao.AccountDao"/>
<!-- 通过 映射文件名 -->
<!--<mapper resource="com/dao/AccountDao.xml"/>-->
<!-- 通过包名 -->
<!--<package name="com.dao"/>-->
</mappers>
</configuration>
- 映射文件
<?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.dao.AccountDao">
<insert id="insert" parameterType="com.entity.Account">
INSERT INTO account VALUES (null, ${uid}, ${money})
<!-- 插入数据完成后, 返回新增数据的主键-->
</selectKey>-->
<selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
select last_insert_id()
</selectKey>
</insert>
</mapper>
- 测试类
public class App2 {
private InputStream in;
private SqlSession sqlSession;
private AccountDao accountDao;
@Before
public void before() {
try {
//加载全局配置文件
in = Resources.getResourceAsStream("SqlMapConfig.xml");
//通过 sqlSessionFactoryBuilder 构造一个 SqlSessionFactory 工厂
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(in);
// 通过工厂 获得 SqlSession 对象
sqlSession = build.openSession(true);
//获得映射的接口对象(代理对象)
accountDao = sqlSession.getMapper(AccountDao.class);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void close() throws IOException {
sqlSession.close();
in.close();
}
@Test
public void insertTest() {
Account account = new Account(null, 2, 100000d);
accountDao.insert(account);
System.out.println(account);
}