介绍
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
MyBatis
下载
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
配置
- conf.xml
<?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><!-- 为User取别名 -->
<typeAlias type="com.fleming.domain.User" alias="_User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<!-- JDBC配置 -->
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${name}" />
<property name="password" value="${pass}" />
</dataSource>
</environment>
</environments>
</configuration>
- userMapper.xml
<?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.fleming.mapping.userMapper">
<select id="getUser" parameterType="int" resultType="_User">
select * from users where id=#{id}
</select>
<insert id="insertUser" parameterType="_User">
insert into users(name,age) values(#{name},#{age})
</insert>
<delete id="delUser" parameterType="int">
delete from users where id=#{id}
</delete>
<update id="updateUser" parameterType="_User">
update users set name=#{name},age=#{age} where id=#{id}
</update>
<select id="getAllUsers" parameterType="_User">
select * from users
</select>
</mapper>
- 利用注解编写接口UserMapperI.java
public interface UserMapperI {
//使用@Insert注解指明add方法要执行的SQL
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int add(User user);
//使用@Delete注解指明deleteById方法要执行的SQL
@Delete("delete from users where id=#{id}")
public int deleteById(int id);
//使用@Update注解指明update方法要执行的SQL
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int update(User user);
//使用@Select注解指明getById方法要执行的SQL
@Select("select * from users where id=#{id}")
public User getById(int id);
//使用@Select注解指明getAll方法要执行的SQL
@Select("select * from users")
public List<User> getAll();
}
使用注解可以方便调用,然后将mapper文件配置到conf.xml中
<mappers>
<mapper resource="com/fleming/mapping/userMapper.xml" />
<mapper class="com.fleming.mapping.UserMapperI" />
</mappers>
测试
-- ----------------------------
-- Table structure for `users`
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `users` VALUES ('1','独孤求败','27'), ('2','独孤求败','27'), ('3','独孤求败','20');
public class MybatisTest {
@Test
public void testGetAll(){
String resource = "conf.xml";
InputStream is = MybatisTest.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
/**
* 映射sql的标识字符串,
* me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
* getAllUsers是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
*/
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
//执行查询操作,将查询结果自动封装成List<User>返回
List<User> lstUsers = mapper.getAll();
//使用SqlSession执行完SQL之后需要关闭SqlSession
sqlSession.close();
for(User user: lstUsers) {
System.out.println(user);
}
}
}
基本入门操作,留作记录。