Mybatis專案建立流程
阿新 • • 發佈:2020-10-29
一、建立maven專案
1、刪除src檔案
2、在pom.xml中配置
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies> <build> <!--在 build中配置resources,來防止我們資源匯出失敗的問題--> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
二、建立module專案
1、配置pox.xml
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
</dependencies>
2、在 resources 資原始檔下建立 核心配置 檔案
2.1 db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/資料庫名?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username=root
password=td725430
2.2 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核心配置檔案--> <configuration> <!--引用外部配置檔案--> <properties resource="db.properties"/> <settings> <!--標準的日誌工廠實現--> <setting name="logImpl" value="STDOUT_LOGGING"/> <!--開啟駝峰命名自動對映--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!--可以給實體類寫別名, 實體類比較少時,使用第一種。 實體類十分多時,建議使用第二種--> <typeAliases> <!--第一種可以DIY(自定義)別名--> <!--<typeAlias type="com.tenton.pojo.User" alias="User"/>--> <!--第二種不能DIY(自定義)別名,如果非要改,需要在實體上增加註解--> <package name="com.tenton.pojo"/> </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> <mapper class="com.tenton.dao.介面名"/> </mappers> </configuration>
3、在Java目錄(com.tenton.utils)下建立工具類 MybatisUtils
public class MybatisUtils {
//提升作用域
private static SqlSessionFactory sqlSessionFactory;
//初始就載入
static {
try {
//使用mybatis
// 第一步 Resources獲取全域性配置檔案(核心配置檔案)mybatis-config.xml
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
/**
*第二步 SqlSessionFactoryBuilder(sqlSession工廠構造器)通過構造器 build
* build 呼叫 build方法
* build 方法 XMLConfigBuilder(XML配置構造器)類,解析了流、環境及配置檔案 (inputStream, environment, properties)
* 解析完成之後,賦值給configuratiion物件(所有配置檔案物件)
* 然後給 build 方法傳遞一個 Configuration 物件解析 Resources 獲取到的全域性配置檔案流inputStream
*第三步 SqlSessionFactoryBuilder(sqlSession工廠構造器)呼叫 build 方法例項化 sqlSessionFactory(sqlSession工廠)
*/
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顧名思義,我們可以從中獲得 SqlSession 的例項。
// SqlSession 提供了在資料庫執行SQL 命令所需的所有方法。
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
}
4、在Java目錄(com.tenton.pojo)下建立實體類 User.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
5、在Java目錄(com.tenton.dao)下建立介面 IUserMapper及對應實現介面中方法的xml檔案 IUserMapper.xml
注意: IUserMapper介面和IUserMapper.xml 要在一個包路徑下
5.1 IUserMapper介面:
package com.tenton.dao;
import com.tenton.pojo.User;
import java.util.List;
import java.util.Map;
public interface IUserMapper {
/**
* 模糊查詢
*/
List<User> getUserLike(String value);
/**
*獲取全部使用者
*/
List<User> getUserList();
/**
* 根據ID查詢使用者
*/
User getUsetById(int id);
/**
* 增加一個使用者
*/
int addUser(User user);
int addUser2(Map<String, Object> map);
/**
* 根據ID刪除使用者
*/
int deleteUser(int id);
/**
* 修改使用者
*/
int updateUser(User user);
}
5.2 IUserMapper.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.tenton.dao.IUserMapper">
<!--select語句查詢:id : 對應namespace中介面中的方法名"
resultType:sql語句執行的返回值-->
<select id="getUserList" resultType="com.tenton.pojo.User">
select * from mybatis.user;
</select>
<select id="getUsetById" resultType="com.tenton.pojo.User">
select * from mybatis.user where id = #{id};
</select>
<select id="getUserLike" resultType="com.tenton.pojo.User">
select * from mybatis.user where name like #{value};
</select>
<!--物件中的屬性,可以直接取出來-->
<insert id="addUser" parameterType="com.tenton.pojo.User">
insert into user(id,name,pwd) values (#{id},#{name},#{pwd});
</insert>
<insert id="addUser2" parameterType="map">
insert into user(id,name,pwd) values (#{userid},#{username},#{userpwd});
</insert>
<update id="updateUser" parameterType="com.tenton.pojo.User">
update user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
<delete id="deleteUser" parameterType="com.tenton.pojo.User">
delete from user where id=#{id};
</delete>
</mapper>
6、在test目錄下建立測試類 IUserMapperTest.java
package com.tenton.dao;
import com.tenton.pojo.User;
import com.tenton.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UserDaoTest {
@Test
public void getUserList(){
SqlSession sqlSession =null;
try {
//第一步:獲取sqlSession物件
sqlSession = MybatisUtils.getSqlSession();
//執行SQL(兩種)
//第一種:getMapper 推薦
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
List<User> userList = mapper.getUserList();
//第二種(不推薦)
// List<User> userList = sqlSession.selectList("com.tenton.dao.IUserMapper.getUserList");
for (User user:userList){
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//關閉sqlSession
sqlSession.close();
}
}
@Test
public void getUserLike(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
List<User> userList = mapper.getUserLike("%尚%");
for (User user:userList) {
System.out.println(user);
//關閉sqlSession
sqlSession.close();
}
}
@Test
public void getUsetById(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
User user = mapper.getUsetById(1);
System.out.println(user);
sqlSession.close();
}
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
int result = mapper.addUser(new User(4, "尚瓊", "lsq01197867"));
if (result > 0){
System.out.println("插入成功!");
}
//提交事務
sqlSession.commit();
sqlSession.close();
}
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
Map<String,Object> map = new HashMap<String,Object>();
map.put("userid",3);
map.put("username","唐東");
map.put("userpwd","td725430");
mapper.addUser2(map);
sqlSession.commit();
sqlSession.close();
}
@Test
public void updateUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
int result = mapper.updateUser(new User(2, "尚瓊", "lsq01197867"));
if (result > 0){
System.out.println("修改成功!");
}
//提交事務
sqlSession.commit();
sqlSession.close();
}
@Test
public void deleteUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
int result = mapper.deleteUser(4);
if (result > 0){
System.out.println("刪除成功!");
}
//提交事務
sqlSession.commit();
sqlSession.close();
}
}