Eclipse下MyBatis簡明教程
工程搭建
創(chuàng)建Java工程
-
導(dǎo)入jar包
把目錄(mybatis-3.2.7/lib)下的文件導(dǎo)入到lib目錄下
asm-3.3.1.jar cglib-2.2.2.jar commons-logging-1.1.1.jar javassist-3.17.1-GA.jar log4j-1.2.17.jar log4j-api-2.0-rc1.jar log4j-core-2.0-rc1.jar mybatis-3.2.7.jar -->mybatis的核心包 mysql-connector-java-5.1.7-bin.jar -->數(shù)據(jù)庫驅(qū)動包 slf4j-api-1.7.5.jar slf4j-log4j12-1.7.5.jar
build path -> add build path
-
配置日志文件
創(chuàng)建config文件夾用于存放配置文件在config文件夾中創(chuàng)建log4j.properties文件,輸入如下內(nèi)容
log4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
-
創(chuàng)建po類
創(chuàng)建user類public class User { private Integer id; private String username; private Date birthday; private String sex; private String address; /** * get/set也需要寫,這里不展示了 **/ }
-
配置數(shù)據(jù)
在config文件夾中創(chuàng)建db.properties文件得运,輸入如下內(nèi)容jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8 jdbc.username=root jdbc.password=123456
-
設(shè)置sql映射文件
在config文件夾中創(chuàng)建user.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="test"> <select id="findUserById" parameterType="java.lang.Integer" resultType="User類的包名.User"> select * from user where id=#{id} </select> </mapper>
-
配置SqlMapConfig.xml
在config文件夾中創(chuàng)建SqlMapConfig.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"/> <environments default="development"> <environment id="development"> <!-- 使用jdbc事務(wù)管理--> <transactionManager type="JDBC" /> <!-- 數(shù)據(jù)庫連接池--> <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="config/User.xml"/> </mappers> </configuration>
-
測試
在測試方法中輸入如下內(nèi)容String resource = "SqlMapConfig.xml"; //通過流將核心配置文件讀取進(jìn)來 InputStream inputStream = Resources.getResourceAsStream(resource); //通過核心配置文件輸入流來創(chuàng)建會話工廠 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); //通過工廠創(chuàng)建會話 SqlSession openSession = factory.openSession(); //第一個參數(shù):所調(diào)用的sql語句= namespace+.+sql的ID User user = openSession.selectOne("test.findUserById", 1); System.out.println(user); openSession.close();
對數(shù)據(jù)庫的增刪改查
1.根據(jù)id查找用戶
在User.xml文件中的
<mapper namespace="test"> </mapper>
節(jié)點(diǎn)內(nèi)添加:
<select id="findUserById" parameterType="int" resultType="User所在的包.User">
select * from user where id=#{id}
</select>
注:以下皆是在此節(jié)點(diǎn)下添加
2.根據(jù)用戶名查找用戶
<select id="findUserByUsername" parameterType="java.lang.String" resultType="User所在的包.User">
select * from user where username like '%${value}%'
</select>
3.添加用戶1
<insert id="insertUser1" parameterType="User所在的包.User">
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
4.添加用戶2
<insert id="insertUser2" parameterType="User所在的包.User">
<selectKey keyProperty="id" order="AFTER" resultType="int">
select LAST_INSERT_ID()
</selectKey>
insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})
</insert>
5.修改用戶
<update id="updateUser" parameterType="User所在的包.User">
update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
</update>
6.刪除用戶
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
測試
private SqlSessionFactory sqlSessionFactory;
@Before
public void createSqlSessionFactory() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test(){
SqlSession sqlSession = null;
sqlSession = sqlSessionFactory.openSession();
//1.根據(jù)id查找用戶
//selectUserById(sqlSession);
//2.根據(jù)用戶名查找用戶
//selectUserByUsername(sqlSession);
//3.添加用戶1
//insertUser1(sqlSession);
//4.添加用戶2
//insertUser2(sqlSession);
//5.修改用戶
//updateUser(sqlSession);
//6.刪除用戶
//deleteUser(sqlSession);
}
//1.根據(jù)id查找用戶
public void selectUserById(SqlSession sqlSession){
User user = sqlSession.selectOne("test.findUserById",10);
System.out.println(user);
sqlSession.close();
}
//2.根據(jù)用戶名查找用戶
public void selectUserByUsername(SqlSession sqlSession){
List<User> users = sqlSession.selectList("test.findUserByUsername","小明");
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
//3.添加用戶1
public void insertUser1(SqlSession sqlSession){
User user = new User();
user.setUsername("美娜");
user.setSex("2");
user.setAddress("beijing");
sqlSession.insert("test.insertUser1",user);
sqlSession.commit();
sqlSession.close();
}
//4.添加用戶2
public void insertUser2(SqlSession sqlSession){
User user = new User();
user.setUsername("小楠");
user.setSex("w");
user.setAddress("beijing");
sqlSession.insert("test.insertUser2",user);
sqlSession.commit();
sqlSession.close();
}
//5.修改用戶
public void updateUser(SqlSession sqlSession){
User user = new User();
user.setUsername("美娜");
user.setSex("w");
user.setAddress("beijing");
user.setId(25);
sqlSession.update("test.updateUser", user);
sqlSession.commit();
sqlSession.close();
}
//6.修改用戶
public void deleteUser(SqlSession sqlSession){
sqlSession.update("test.deleteUser", 25);
sqlSession.commit();
sqlSession.close();
}
Mapper動態(tài)代理
接口文件
Mapper接口方法名和Mapper.xml中定義的statement的id相同
Mapper接口方法的輸入?yún)?shù)類型和mapper.xml中定義的statement的parameterType的類型相同
-
Mapper接口方法的輸出參數(shù)類型和mapper.xml中定義的statement的resultType的類型相同
public interface UserMapper { public User findUserById(Integer id); public List<User> findUserByUsername(String userName); }
映射文件
接口的名稱和映射文件名稱除擴(kuò)展名外要完全相同
接口和映射文件要放在同一個目錄下
-
namespace的值為UserMapper接口路徑
<?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="UserMapper所在的包.UserMapper"> <!-- 1.通過id查找用戶 --> <select id="findUserById" parameterType="int" resultType="User所在的包.User"> select * from user where id=#{id} </select> <!-- 2.根據(jù)用戶名查找用戶 --> <select id="findUserByUsername" parameterType="java.lang.String" resultType="User所在的包.User"> select * from user where username like '%${value}%' </select> </mapper>
加載映射文件
-
單個加載
<mapper class="UserMapper所在的包.UserMapper"/>
批量加載
1. 接口的名稱和映射文件名稱除擴(kuò)展名外要完全相同
2. 接口和映射文件要放在同一個目錄下
<package name="接口所在的包名"/>
測試
private SqlSessionFactory sqlSessionFactory;
@Before
public void createSqlSessionFactory() throws IOException {
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void test() throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 1.根據(jù)id查找用戶
// selectUserById(userMapper);
// 2.根據(jù)用戶名查找用戶
// selectUserByUsername(userMapper);
}
// 1.根據(jù)id查找用戶
public void selectUserById(UserMapper userMapper) {
User user = userMapper.findUserById(1);
System.out.println(user);
}
// 2.根據(jù)用戶名查找用戶
public void selectUserByUsername(UserMapper userMapper) {
List<User> users = userMapper.findUserByUsername("小明");
for (User user : users) {
System.out.println(user);
}
}