介紹
MyBatis 是一款優(yōu)秀的持久層框架麸俘,它支持定制化 SQL从媚、存儲(chǔ)過程以及高級(jí)映射。MyBatis 避免了幾乎所有的 JDBC 代碼和手動(dòng)設(shè)置參數(shù)以及獲取結(jié)果集各谚。MyBatis 可以使用簡(jiǎn)單的 XML 或注解來配置和映射原生信息昌渤,將接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java對(duì)象)映射成數(shù)據(jù)庫中的記錄。
下載
mybatis-3.4.5
mysql-jdbc-connector
如果你使用的Maven構(gòu)建可以直接配置dependency冗酿。
<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方法要執(zhí)行的SQL
@Insert("insert into users(name, age) values(#{name}, #{age})")
public int add(User user);
//使用@Delete注解指明deleteById方法要執(zhí)行的SQL
@Delete("delete from users where id=#{id}")
public int deleteById(int id);
//使用@Update注解指明update方法要執(zhí)行的SQL
@Update("update users set name=#{name},age=#{age} where id=#{id}")
public int update(User user);
//使用@Select注解指明getById方法要執(zhí)行的SQL
@Select("select * from users where id=#{id}")
public User getById(int id);
//使用@Select注解指明getAll方法要執(zhí)行的SQL
@Select("select * from users")
public List<User> getAll();
}
使用注解可以方便調(diào)用净刮,然后將mapper文件配置到conf.xml中
<mappers>
<mapper resource="com/fleming/mapping/userMapper.xml" />
<mapper class="com.fleming.mapping.UserMapperI" />
</mappers>
測(cè)試
-- ----------------------------
-- 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','獨(dú)孤求敗','27'), ('2','獨(dú)孤求敗','27'), ('3','獨(dú)孤求敗','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的標(biāo)識(shí)字符串暑认,
* me.gacl.mapping.userMapper是userMapper.xml文件中mapper標(biāo)簽的namespace屬性的值粮彤,
* getAllUsers是select標(biāo)簽的id屬性值尘惧,通過select標(biāo)簽的id屬性值就可以找到要執(zhí)行的SQL
*/
UserMapperI mapper = sqlSession.getMapper(UserMapperI.class);
//執(zhí)行查詢操作漾狼,將查詢結(jié)果自動(dòng)封裝成List<User>返回
List<User> lstUsers = mapper.getAll();
//使用SqlSession執(zhí)行完SQL之后需要關(guān)閉SqlSession
sqlSession.close();
for(User user: lstUsers) {
System.out.println(user);
}
}
}
基本入門操作核芽,留作記錄哮独。