目录
第六步:配置UserMapper.xml在resources下的映射路径。
1. 简介
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Ordinary Java Object,普通的 Java对象)映射成数据库中的记录。
2. 搭建第一个MaBatis工程
整体项目结构:
第一步:创建一个JavaMaven项目
第二步:导入pom.xml坐标(jar包引用)
<!--mybatis的依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--msyql的驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!--日志:记录应用程序所有的执行过程--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
第三步:创建MyBatis核心配置文件
(1)在resources下创建mybatis的配置文件,命名规范为mybatis-config.xml。
(2)配置mybatis-config.xml,可以去mybatis官方网站去复制。
官网链接:https://mybatis.org/mybatis-3/zh/getting-started.html
<?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> <!--数据库配置信息,一旦和spring整合结束,这些配置有spring进行管理--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://locallhost:3306/mybtis"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> </configuration>
第四步:创建数据库表和实体类及其Dao层接口
(1)创建数据库表:
(2)创建实体类及Dao层接口
第五步:创建实体类映射文件
(1)在resources目录下按下图一层一层创建文件(new directory)
(2)在目录下创建实体类映射文件(file),命名方式为UserDao.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.xs.dao.UserDao"> <insert id="addUser" parameterType="com.xs.pojo.User"> insert into user values (null,#{uname},#{pwd}); </insert> </mapper>
注:namespace命名空间为java目录下xxxDao的全限定类名。
id值必须为xxxDao内的方法名。
parameterType标明方法中的参数类型。
sqL语句内的values参数,自增属性为null,其他属性为#{字段名}。
第六步:配置UserMapper.xml在resources下的映射路径。
在mybits-config.xml中的<configuration></configuration>标签内去配置UserMapper.xml在resources下的映射路径。
<!—添加映射信息--> <mappers> <mapper resource="com/xs/dao/UseMapper.xml"></mapper> </mappers>
第七步:运行测试
@Test public void addUser() throws IOException { //读取配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); //创建核心SqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); //通过SqlSessionFactory创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); //通过SqlSession获取XXXDao UserDao mapper = sqlSession.getMapper(UserDao.class); //增加用户 User user=new User(); user.setUname("张三"); user.setPwd("145235"); //通过XXXDao执行增删改查方法 mapper.addUser(user); //提交事务 sqlSession.commit(); }
3.上例完整项目代码展示
项目结构:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zx</groupId> <artifactId>20210707_Mybatis02</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!--mybatis的依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.7</version> </dependency> <!--msyql的驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <!--日志:记录应用程序所有的执行过程--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </project>
UserDao接口:
package com.xs.dao; import com.xs.pojo.User; import java.util.List; public interface UserDao { void addUser(User user);//增 void deleteUser(int id);//删 根据id删除 void updateUser(User user);//改 List<User> selectUser();//查所有 User selectOneUser(int id);//查询一条 }
User实体类:
package com.xs.pojo; public class User { private int id; private String uname; private String pwd; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public User() { } public User(String uname, String pwd) { this.uname = uname; this.pwd = pwd; } public User(int id, String uname, String pwd) { this.id = id; this.uname = uname; this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", uname='" + uname + '\'' + ", pwd='" + pwd + '\'' + '}'; } }
UserDao映射文件——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="com.xs.dao.UserDao"> <!-- 增加--> <insert id="addUser" parameterType="com.xs.pojo.User"> insert into user values (null,#{uname},#{pwd}); </insert> <!-- 删除--> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> <!-- 修改--> <update id="updateUser" parameterType="com.xs.pojo.User"> update user set uname=#{uname},pwd=#{pwd} where id=#{id} </update> <!-- 查--> <select id="selectUser" resultType="com.xs.pojo.User" > select * from user </select> <!-- 查一条--> <select id="selectOneUser" resultType="com.xs.pojo.User" > select * from user where id=#{id} </select> </mapper>
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> <!--数据库配置信息,一旦和spring整合结束,这些配置有spring进行管理--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybtis?useUncode=ture&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/xs/dao/UserMapper.xml"></mapper> </mappers> </configuration>
运行测试代码——MybatisTest.java:
package com.xs.test; import com.xs.dao.UserDao; import com.xs.pojo.User; 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 org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.List; public class MybatisTest { @Test public void addUser() throws IOException { //读取配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); //创建核心SqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); //通过SqlSessionFactory创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); /**********************方式一***********************/ //通过SqlSession获取XXXDao UserDao mapper = sqlSession.getMapper(UserDao.class); //增加用户 User user=new User(); user.setUname("张大奎"); user.setPwd("145235"); //通过XXXDao执行增删改查方法 mapper.addUser(user); /****************************************************/ //提交事务 sqlSession.commit(); //关闭sqlSession sqlSession.close(); } @Test public void addUse() throws IOException { //读取mybatis-config.xml配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); //创建核心SqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); //通过SqlSessionFactory创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); /**********************方式二***********************/ /* 以插入为例 sqlSession.insert(String:命名空间.id值,参数); */ //增加用户 User user=new User("王磊","666"); //user.setUname("吴太上"); //user.setPwd("58458"); //""内为UserMapper.xml内的"namespace.id" sqlSession.insert("com.xs.dao.UserDao.addUser",user); /****************************************************/ //提交事务 sqlSession.commit(); //关闭sqlSession sqlSession.close(); } @Test public void deleteUser() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /**********************方式一***********************/ //通过SqlSession获取XXXDao UserDao mapper = sqlSession.getMapper(UserDao.class); //删除用户 mapper.deleteUser(6); /****************************************************/ sqlSession.commit(); sqlSession.close(); } @Test public void updateUser() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /**********************方式一***********************/ //通过SqlSession获取XXXDao UserDao mapper = sqlSession.getMapper(UserDao.class); //修改用户信息 User user=new User(); user.setId(8); user.setUname("刘桑"); user.setPwd("5462"); mapper.updateUser(user); /****************************************************/ sqlSession.commit(); sqlSession.close(); } @Test public void selectUser() throws IOException { InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /**********************方式一***********************/ //通过SqlSession获取XXXDao UserDao mapper = sqlSession.getMapper(UserDao.class); //查询所有用户 mapper.selectUser(); /****************************************************/ sqlSession.commit(); sqlSession.close(); } @Test public void selectOneUser() throws IOException { //读取mybatis-config.xml配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); //创建核心SqlSessionFactory SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream); //通过SqlSessionFactory创建SqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); /**********************方式一***********************/ //通过SqlSession获取XXXDao UserDao mapper = sqlSession.getMapper(UserDao.class); //查询所有用户 mapper.selectOneUser(7); /****************************************************/ //提交事务 sqlSession.commit(); //关闭sqlSession sqlSession.close(); } }