Mybatis用法详解(配置和注解的使用)

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

mybatis是持久层框架

使用方法(基于xml配置)

1.添加依赖(Maven)

<!--数据库相关, mysql, mybatis-->    <!--jdbc连接-->    <dependency>        <groupId>mysql</groupId>        <artifactId>mysql-connector-java</artifactId>        <version>5.1.37</version>    </dependency>    <!--spring-mybatis  -->    <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis-spring</artifactId>        <version>${mybatis-spring-version}</version>    </dependency>    <!--mybatis-->    <dependency>        <groupId>org.mybatis</groupId>        <artifactId>mybatis</artifactId>        <version>${mybatis-version}</version>    </dependency>     <!--反射生成实体类-->    <dependency>        <groupId>org.mybatis.generator</groupId>        <artifactId>mybatis-generator-core</artifactId>        <version>1.3.2</version>    </dependency>

2.建立数据库、表

CREATE DATABASE testdatabase;USE testdatabase;CREATE TABLE user(id INT PRIMARY KEY AUTO_INCREMENT, userName VARCHAR(20) NOT NULL, userAge INT NOT NULL);
INSERT INTO user(userName, userAge) VALUES('Xiaoxin', 21);INSERT INTO user(userName, userAge) VALUES('Xiaoming', 22);

3.表的实体类

package com.xiaoxin.demo.dto; public class User {	private int id;    private String userName;    private int userAge;	public int getId() {		return id;	}	public void setId(int id) {		this.id = id;	}	public String getUserName() {		return userName;	} 	public void setUserName(String userName) {		this.userName = userName;	}	public int getUserAge() {		return userAge;	}	public void setUserAge(int userAge) {		this.userAge = userAge;	}	@Override	public String toString() {		return "User [id=" + id + ", userName=" + userName + ", userAge=" + userAge + "]";	}}

4.添加Mybatis的配置文件

<?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>    <typeAliases>         <typeAlias alias="User" type="com.xiaoxin.demo.dto.User"/>     </typeAliases> 	<!-- 数据库环境配置-->    <environments default="development">        <environment id="development">        <!-- jdbc管理-->        <transactionManager type="JDBC"/>         <!-- 用什么连接池-->            <dataSource type="POOLED">             <!-- jdbc驱动-->            <property name="driver" value="com.mysql.jdbc.Driver"/>            <!-- 数据库名字url-->            <property name="url" value="jdbc:mysql://127.0.0.1:3306/testdatabase" />            <!-- 数据库用户-->            <property name="username" value="root"/>            <!-- 数据库用户密码-->            <property name="password" value=""/>            </dataSource>        </environment>    </environments>    <!-- 把User.xml注册到mybatis的配置文件中,User.xml下面配置 -->    <mappers>        <mapper resource="com/xiaoxin/demo/dto/User.xml"/>    </mappers></configuration>

5.定义操作user表的映射文件,第四步已经注册到mybatis的配置文件中去了

<?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"><!-- 定义操作user表的sql映射文件userMapper.xml  --><mapper namespace="com.xiaoxin.demo.dto">    <select id="selectUserByID" parameterType="int" resultType="User">        select * from `User` where id = #{id}    </select></mapper>

6.测试

package com.xiaoxin.demo.dto; import java.io.Reader; 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; public class TestUser {	@Test	public void testUser() throws Exception{		 SqlSessionFactory sqlSessionFactory;	     Reader reader; 	     String resource = "spring/configuration.xml";	     //加载一个流	     reader= Resources.getResourceAsReader(resource);	     //生成sqlSessionFactory工厂	     sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);	     SqlSession session = sqlSessionFactory.openSession();	     User user =(User) session.selectOne("com.xiaoxin.demo.dto.selectUserByID", 1);	     System.out.print(user.toString());	    session.close();			}	 }

连接数据库成功查询到数据

CRUD操作汇总

<?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"><!-- 定义操作users表的sql映射文件userMapper.xml  --><mapper namespace="com.xiaoxin.demo.dto">    <!--查询  -->     <select id="selectUserAll" parameterType="int" resultType="User">        select * from user    </select>    <!--插入  -->    <insert id="insertUser" parameterType="com.xiaoxin.demo.dto.User">    		insert into user(userName,userAge) values(#{userName},#{userAge});    </insert>	<!--更新  -->    <update id="updateUser" parameterType="com.xiaoxin.demo.dto.User">    		update user set userAge=#{userAge},userName=#{userName} where id=#{id}    </update>    <!--删除  -->    <delete id="deleteUser" parameterType="int">    	delete from user where id=#{id}    </delete>    </mapper>

测试

package com.xiaoxin.demo.dto; import java.io.Reader;import java.util.List; 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; public class TestUser {	@Test	public void testUser() throws Exception{		 SqlSessionFactory sqlSessionFactory;	     Reader reader; 	     String resource = "spring/configuration.xml";	     //加载一个流	     reader= Resources.getResourceAsReader(resource);	     //生成sqlSessionFactory工厂	     sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);	     SqlSession session = sqlSessionFactory.openSession();	     //插入//	     User user1 = new User();//	     user1.setUserName("Xiaohong");//	     user1.setUserAge(20);//	     session.insert("com.xiaoxin.demo.dto.insertUser", user1);//	     // session.commit();一定要执行不然在数据库中没有信息!!!!!//	     session.commit();	    //更新	     //把Xiaohong的姓名改为Xiaohong101年龄改为44 Xiaohong的id是13//	     User user3 = new User();//	     user3.setUserName("Xiaohong101");//	     user3.setUserAge(44);//	     user3.setId(16);//	     session.update("com.xiaoxin.demo.dto.updateUser",user3);//	     session.commit();	     	    //删除	     session.delete("com.xiaoxin.demo.dto.deleteUser",16);	     session.commit();	     //查询数据库全部的信息	     List<User> user2 = session.selectList("com.xiaoxin.demo.dto.selectUserAll");	     for(User user:user2){	    	 System.out.println(user.toString());	     }	    session.close();			}	 }

以上自己测试过全部成功,但是xml的配置过程中自己出错了很多,调试了很多次才成功调试出来,下面学习基于注解的写法

Mybatis的注解用法

1.定义SQL映射的接口

package com.xiaoxin.demo.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update; import com.xiaoxin.demo.dto.User; public interface UserMapper {	@Select("select * from user")	public List<User> getSelectUser();	@Update("UPDATE user set userName=#{userName},userAge=#{userAge} where id=#{id}")	public void getUpdateUser(User user);	@Insert("insert into user(userName,userAge) values(#{userName},#{userAge});")	public void getInsertUser(User user);	@Delete("DELETE FROM user where id=#{id}")	public void getDeleteUser(int id);	 }

2.在mybatis的配置文件中注册这个映射接口(注意是class!!)

 <mappers>        <mapper resource="com/xiaoxin/demo/dto/User.xml"/>        <mapper class="com.xiaoxin.demo.mapper.UserMapper"></mapper>    </mappers>

在Dao类中调用(这里是测试)

package com.xiaoxin.demo.dto; import java.io.IOException;import java.io.Reader;import java.util.List; 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 com.xiaoxin.demo.mapper.UserMapper; public class TestUserAnnotation {		@Test	public void testUser() throws IOException{				 SqlSessionFactory sqlSessionFactory;	     Reader reader; 	     String resource = "spring/configuration.xml";	     //加载一个流	     reader= Resources.getResourceAsReader(resource);	     //生成sqlSessionFactory工厂	     sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);	     SqlSession session = sqlSessionFactory.openSession();	     	     UserMapper userMapper = session.getMapper(UserMapper.class);	     //插入//	     User user = new User();//	     user.setUserName("xinxin");//	     user.setUserAge(20);//	     userMapper.getInsertUser(user);//	     session.commit();	     //删除//	     userMapper.getDeleteUser(21);//	     session.commit();	     //更新将id为19的姓名不变 年龄改为23//	     User user = new User();//	     user.setId(19);//	     user.setUserName("xinxin");//	     user.setUserAge(23);//	     userMapper.getUpdateUser(user);//	     session.commit();	     //查询	     List<User> users = userMapper.getSelectUser();	     for(User user2 :users){	    	 System.out.println(user2.toString());	     }	     session.close();	} }

测试成功

点这里可以跳转到人工智能网站

发表评论