Mybatis 使用原生接口
作者:互联网
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();
}
标签:原生,userName,String,xml,userid,接口,Mybatis,userPwd,public 来源: https://www.cnblogs.com/lwx11111/p/16226704.html