MyBatis基礎框架
阿新 • • 發佈:2020-07-24
一個MyBatis基礎框架
1. 搭建資料庫
CREATE DATABASE `mybatis`; USE `mybatis`; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(20) NOT NULL, `name` varchar(30) DEFAULT NULL, `pwd` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user`(`id`,`name`,`pwd`) values (1,'hello','123456'),(2,'張 三','abcdef'),(3,'李四','987654');
2. . 編寫MyBatis核心配置檔案(如:mybatis-config.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> <!--在資源目錄建立db.properties檔案,記錄資料庫資訊--> <properties resource="db.properties"/> <!--預設使用id為development的環境--> <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> <!--或者使用test環境配置,不建立獨立的db.properties檔案--> <environment id="test"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/lf/dao/UserMapper.xml"/> </mappers> </configuration>
3. 編寫MyBatis工具類(如:MybatisUtils.java)
package com.lf.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.IOException; import java.io.InputStream; public class MybatisUtils { //提升作用域 private static SqlSessionFactory sqlSessionFactory; static{ try { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } //獲取SqlSession連線 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
4. 建立實體類(如:User.java)
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密碼
//構造,有參,無參
//set/get
//toString()
}
5. 編寫Mapper介面類 (如:UserMapper)
package com.lf.dao;
import com.lf.pojo.User;
import java.util.List;
public interface UserMapper {
//查詢全部使用者
List<User> getUserList();
//根據欄位查詢使用者
List<User> getUserLike(String value);
//根據ID查詢使用者
User getUserById(int id);
//insert一個使用者
int addUser(User user);
//修改使用者
int updateUser(User user);
//刪除一個使用者
int deleteUser(int id);
}
6. 編寫Mapper.xml配置檔案(如: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.lf.dao.UserMapper">
<select id="getUserLike" resultType="com.lf.pojo.User">
select * from mybatis.user where name like "%"#{value}"%"
</select>
<select id="getUserList" resultType="com.lf.pojo.User">
select * from mybatis.user
</select>
<insert id="addUser" parameterType="com.lf.pojo.User">
insert into mybatis.user (id,name,pwd) values (#{id},#{name },#{pwd});
</insert>
<update id="updateUser" parameterType="com.lf.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
</mapper>
7. 編寫測試類 (可在test資料夾中測試)
package com.lf.dao;
import com.lf.pojo.User;
import com.lf.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
//查詢所有姓藍的使用者
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserLike("藍%");
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
//查詢所有資料
@Test
public void test() {
//第一步:獲得SqlSession物件
SqlSession sqlSession = MybatisUtils.getSqlSession();
try {
UserMapper userDao = sqlSession.getMapper(UserMapper.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//關閉SqlSession
sqlSession.close();
}
}
}