Mybatis 使用原生介面
阿新 • • 發佈:2022-05-05
1.在resources檔案下新建mysql.properties檔案
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/user?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
username=root
password=lwxMysql
2.在resources檔案下新建config.xml檔案 並加入以下標籤
<properties resource="mysql.properties"></properties> <!-- mybatis執行環境--> <environments default="development"> <environment id="development"> <!-- JDBC事務管理--> <transactionManager type="JDBC"></transactionManager> <!-- 資料庫連線池--> <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>
3.資料庫創表,寫資料
4.新建實體類User
package entity; public class User { private int userid; private String userName; private String userPwd; public User(int id, String userName, String userPwd) { this.userid=id; this.userName = userName; this.userPwd = userPwd; } public String getUserName() { return userName; } public int getUserid() { return userid; } public void setUserid(int userid) { this.userid = userid; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } }
5.在mapper包下建立my1Mapper.xml
注意事項:namespace要用.到Mapper名字
<?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="mapper.my1Mapper"> <!-- id呼叫mybatis方法需要用到的引數--> <!-- parameterType呼叫時引數型別--> <insert id="save" parameterType="entity.User" > insert into login(userid,userName,userPwd) values (#{userid},#{userName},#{userPwd}) </insert> </mapper>
6.在config.xml檔案中註冊my1Mapper.xml
注意事項:路徑用/
<mappers>
<!-- 註冊my1Mapper-->
<mapper resource="mapper/my1Mapper.xml"></mapper>
</mappers>
7.新建測試類來測試
public void fun1(){
/**
* 使用原生介面
* 1.在pom.xml中新增依賴
* 2.建立mybatis配置檔案
* 3.將sql語句寫在Mapper.xml中 並在配置檔案中註冊
* 4.載入mybatis配置檔案
* 5.得到SqlSession物件
* 6.呼叫Mapper中的sql語句
* 7.傳入引數並執行
*/
InputStream is= App.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder ssfb=new SqlSessionFactoryBuilder();
SqlSessionFactory ssf=ssfb.build(is);
SqlSession sqlSession=ssf.openSession();
//呼叫insert
String statement="mapper.my1Mapper.save";
//存入的引數
User m=new User(8,"lwx","lop");
sqlSession.insert(statement,m);
sqlSession.commit();
sqlSession.close();
}