MyBatis使用小结

  • Post author:
  • Post category:其他


使用小结:

1、配置数据库连接文件con.xml

2、配置sql映射文件.xml 或者使用注解接口文件

3、写pojo 的java文件

4、调用mybatis

001
<?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://localhost:3306/springboot?useSSL=false" />
                 <property name="username" value="root" />
                 <property name="password" value="aer442" />
                  
             </dataSource>
         </environment>
     </environments>
     
     <mappers>
         <!-- 注册userMapper.xml文件, 
         userMapper.xml位于me.gacl.mapping这个包下,所以resource写成me/gacl/mapping/userMapper.xml-->
         <mapper resource="userMapper.xml"/>
         <mapper class="UserMapperI"/>
      </mappers>
     
 </configuration>
002
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

 public interface UserMapperI {
 
     //使用@Insert注解指明add方法要执行的SQL
     @Insert("insert into t_user(name, age) values(#{name}, #{age})")
     @Options(useGeneratedKeys=true)
     public int add(User user);
     
     //使用@Delete注解指明deleteById方法要执行的SQL
     @Delete("delete from users where id=#{id}")
     public int deleteById(int id);
     
     //使用@Update注解指明update方法要执行的SQL
     @Update("update users set name=#{name},age=#{age} where id=#{id}")
     public int update(User user);
     
     //使用@Select注解指明getById方法要执行的SQL
     @Select("select * from users where id=#{id}")
     public User getById(int id);
     
     //使用@Select注解指明getAll方法要执行的SQL
     @Select("select * from users")
     public List<User> getAll();
 }
002-001
<?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="me.gacl.mapping.userMapper">
     <select id="getUser"   
         resultType="User">
         select * from t_user where name like #{name}
     </select>
     <insert id="addUser" parameterType="User" keyProperty="id" useGeneratedKeys="true">
      insert into t_user(name,age) values (#{name},#{age})
     </insert>
     
 </mapper>
003
  /**
   * @author gacl
   * users表所对应的实体类
   */
  public class User {
  
      //实体类的属性和表的字段名称一一对应
     private int id;
     private String name;
     private int age;
 
     public int getId() {
         return id;
     }
 
     public void setId(int id) {
         this.id = id;
     }
 
     public String getName() {
         return name;
     }
 
     public void setName(String name) {
         this.name = name;
     }
 
     public int getAge() {
         return age;
     }
 
     public void setAge(int age) {
         this.age = age;
     }
 
     @Override
     public String toString() {
         return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
     }
 }
004
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		//System.out.println("hello world!MyBatis|!!!!");
		/*
        //mybatis的配置文件
        //String resource = "conf.xml";
        //使用类加载器加载mybatis的配置文件(它也加载关联的映射文件)
        //InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession的工厂
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //使用MyBatis提供的Resources类加载mybatis的配置文件(它也加载关联的映射文件)
        //Reader reader = Resources.getResourceAsReader(resource); 
        //构建sqlSession的工厂
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //创建能执行映射文件中sql的sqlSession
        //SqlSession session = sessionFactory.openSession();
        /**
         * 映射sql的标识字符串,
         * me.gacl.mapping.userMapper是userMapper.xml文件中mapper标签的namespace属性的值,
         * getUser是select标签的id属性值,通过select标签的id属性值就可以找到要执行的SQL
         */
        //String statement = "me.gacl.mapping.userMapper.getUser";//映射sql的标识字符串
        //执行查询返回一个唯一user对象的sql
        //User user = session.selectOne(statement, 12);
        //System.out.println(user);
		
		//Test.addUser();
		//Test.addUserByNote();
		Test.searchUser();
        

	}
	
	public static void searchUser() {
		
		String resource = "conf.xml" ;
		InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		String statement = "me.gacl.mapping.userMapper.getUser";
		User user1 = new User();
		user1.setName("abc");
		user1.setAge(13);
		List<User> u = session.selectList(statement, "a%");//返回一个集合参数是一个字符串
	      //User user = session.selectOne(statement,user1) ; //查询返回单个对象,参数是一个对象
	    System.out.println(u);
	}
	
	public static void addUserByNote() {
		
		String resource = "conf.xml" ;
		InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		UserMapperI m = session.getMapper(UserMapperI.class);
		
		User user = new User();
		user.setName("dddd");
		user.setAge(38);
		int add = m.add(user) ;
		//session.g
	    //session.commit();
		session.close();
		System.out.println(user.getId());
		
		
	}
	public static void addUser() {
		
		//SqlSession sqlSession = MyBatisU
		
		String resource = "conf.xml" ;
		InputStream is = Test.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		String statement = "me.gacl.mapping.userMapper.addUser";
		User u = new User();
		u.setAge(30);
		u.setName("aerly");
		int r = session.insert(statement,u);
		session.commit();
		session.close();
		System.out.println(u.getId());
		//System.out.println(r);
		
	}

}

参考文件:

1、

MyBatis学习总结 一


2、

MyBatis学习总结 二


3、

MyBatis 文档说明