Mybatis基本使用
Posted 逆梦
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis基本使用相关的知识,希望对你有一定的参考价值。
1、创建maven项目,导入mybatis依赖。
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4.SNAPSHOOT</version> </dependency>
2、创建MybatisConfig.xml配置连接文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org/DTD Config 3.0" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- MyBatis的全局配置文件 --> <configuration > <!-- 1.配置环境,可配置多个环境(比如:develop开发、test测试) --> <environments default="develop"> <environment id="develop"> <!-- 1.1.配置事务管理方式:JDBC/MANAGED JDBC:将事务交给JDBC管理(推荐) MANAGED:自己管理事务 --> <transactionManager type="JDBC"></transactionManager> <!-- 1.2.配置数据源,即连接池 JNDI/POOLED/UNPOOLED JNDI:已过时 POOLED:使用连接池(推荐) UNPOOLED:不使用连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/user-mode?characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value="1234qwer"/> </dataSource> </environment> </environments> <!-- 2.导入Mapper配置文件,如果mapper文件有多个,可以通过多个mapper标签导入--> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
3、创建User用户实体类
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User
private Long id;
/**
* 名称
*/
private String name;
/**
* 邮箱
*/
private String email;
/**
* 手机号
*/
private String phoneNumber;
4、创建用户model接口
@Mapper public interface UserMapper List<User> getPageUser(@Param("name") String name); void insertUser(User user); void updateUser(User user); void deletetUser(Long userId);
5、创建映射文件UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.itmy.dao.UserMapper"> <resultMap id="userRmap" type="com.itmy.model.entity.User"> <result jdbcType="VARCHAR" javaType="java.lang.String" column="name" /> </resultMap> <select id="getPageUser" resultType="com.itmy.model.entity.User" parameterType="string"> select * from tb_user <where> <if test="name != null and \'\' != name"> name like CONCAT(\'%\',#name,\'%\'); </if> </where> </select> <insert id="insertUser" parameterType="com.itmy.model.entity.User"> INSERT INTO `tb_user` (`name`, `account`,`password`, `email`,phone_number,remark) VALUES (#name, #account, #password, #email,#phoneNumber,#remark); </insert> <update id="updateUser" parameterType="com.itmy.model.entity.User"> UPDATE tb_user <set> <if test="name != null and \'\' != name"> name = #name, </if> <if test="account != null and \'\' != account"> account = #account, </if> <if test="password != null and \'\' != password"> password = #password, </if> <if test="email != null and \'\' != email"> email = #email, </if> <if test="phoneNumber != null and \'\' != phoneNumber"> phone_number = #phoneNumber, </if> <if test="remark != null and \'\' != remark"> remark = #remark, </if> </set> where id = #id </update> <delete id="deletetUser" parameterType="java.lang.Long"> DELETE FROM tb_user WHERE id = #userId </delete> </mapper>
6、在测试类中编写测试文件MTest.java
public class Test InputStream inputStream; SqlSession sqlSession; @Before public void beforeSql() throws IOException inputStream = Resources.getResourceAsStream("MybatisConfig.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); @org.junit.Test public void querySql() UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> pageUser = userMapper.getPageUser(null); for (int i = 0; i < pageUser.size(); i++) System.out.println(pageUser.get(i)); @org.junit.Test public void insertSql() UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user=new User(); user.setAccount("aaaaa@qq.com"); user.setEmail("aaaaa@qq.com"); user.setName("掌声"); user.setPassword("SDWAR!@"); user.setPhoneNumber("12345"); user.setRemark("测试优化信息"); userMapper.insertUser(user); sqlSession.commit(); System.out.println(); @org.junit.Test public void updateSql() UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user=new User(); user.setAccount("bbabbb@qq.com"); user.setEmail("bbbabb@qq.com"); user.setName("掌声bb"); user.setPassword("SDbbWAR!@"); user.setPhoneNumber("12345"); user.setRemark("测试优化b信息"); user.setId(5L); userMapper.updateUser(user); System.out.println(); sqlSession.commit(); @org.junit.Test public void deleteSql() UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.deletetUser(6L); System.out.println(); sqlSession.commit(); @After public void afterSql() throws IOException sqlSession.close(); inputStream.close();
mybatis基本使用
一、介绍
持久层框架
官方文档:http://www.mybatis.org/mybatis-3/zh/index.html
二、基本使用
1.创建项目和模块
2.添加pom.xml
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.17</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> </dependencies>
3.添加配置
resoucecs/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> <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://192.168.137.101:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="mysql"/> </dataSource> </environment> </environments> </configuration>
4.创建库和表
mysql>create database mybatis ; mysql>use mybatis ; mysql>create table users(id int primary key auto_increment , name varchar(20) ,age int) ; mysql>desc users ;
5.测试连接
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 App { public static void main(String[] args) { try { //指定配置文件的路径(类路径) String resource = "mybatis-config.xml"; //加载文件 InputStream inputStream = Resources.getResourceAsStream(resource); //创建会话工厂Builder,相当于连接池 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream); //通过sf开启会话,相当于打开连接。 SqlSession s = sf.openSession(); System.out.println(s); } catch (Exception e) { e.printStackTrace(); } } }
6.编写mapper文件
6.1)创建User类,和users对应
public class User { private Integer id ; private String name ; private int age ; //get/set }
6.2)创建UserMapper.xml,存放在resources/目录下
resources/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="users"> <!-- 定义insert语句 --> <insert id="insert"> insert into users(name,age) values(#{name},#{age}) </insert> </mapper>
7.在resources/mybatis-config.xml文件中引入mapper的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> <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://192.168.137.101:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="mysql"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
8.编写单元测试,实现插入.
@Test public void insert() throws Exception { //指定配置文件的路径(类路径) String resource = "mybatis-config.xml"; //加载文件 InputStream inputStream = Resources.getResourceAsStream(resource); //创建会话工厂Builder,相当于连接池 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream); //通过sf开启会话,相当于打开连接。 SqlSession s = sf.openSession(); User u = new User(); u.setName("jerry"); u.setAge(2); s.insert("users.insert", u); s.commit(); s.close(); }
9.完成update-selectOne-selectAll操作。
9.1)编写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="users"> <insert id="insert"> insert into users(name,age) values(#{name},#{age}) </insert> <update id="update"> update users set name = #{name} , age = #{age} where id = #{id} </update> <!-- selectOne --> <select id="selectOne" parameterType="int" resultType="com.niu.mybatisdemo.domain.User"> select * from users where id = #{id} </select> <!-- selectAll --> <select id="selectAll" resultType="com.niu.mybatisdemo.domain.User"> select * from users </select> </mapper>
9.2)编写测试程序
@Test public void insert() throws Exception { //指定配置文件的路径(类路径) String resource = "mybatis-config.xml"; //加载文件 InputStream inputStream = Resources.getResourceAsStream(resource); //创建会话工厂Builder,相当于连接池 SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream); //通过sf开启会话,相当于打开连接。 SqlSession s = sf.openSession(); User u = new User(); u.setName("jerry"); u.setAge(2); s.insert("users.insert", u); s.commit(); s.close(); }
@Test public void update() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream); SqlSession s = sf.openSession(); User u = new User(); u.setId(1); u.setName("tomas"); u.setAge(32); s.update("users.update", u); s.commit(); s.close(); }
@Test public void selectOne() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream); SqlSession s = sf.openSession(); User user = s.selectOne("users.selectOne",1); System.out.println(user.getName()); s.commit(); s.close(); }
@Test public void selectAll() throws Exception { String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(inputStream); SqlSession s = sf.openSession(); List<User> users = s.selectList("users.selectAll"); for(User uu : users){ System.out.println(uu.getName() + "," + uu.getAge()); } s.commit(); s.close(); }
三、复杂应用
以上是关于Mybatis基本使用的主要内容,如果未能解决你的问题,请参考以下文章