The mybatis framework implements the addition, deletion, modification and query of data based on annotations

Writing Mybatis code, unlike spring, does not need to import plug-ins, just import the shelf package;

Import the mybatis shelf package under lib: mybatis-3.1.1.jar
mysql driver shelf package: mysql-connector-java-5.1.6-bin.jar

 

Create an xml configuration file in the src directory: conf.xml, which is some configuration to connect to the database:

copy code
<?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: development mode
    work: work mode
    default = "development", id = "development" , the two attribute values ​​must be the same
      -->    
     <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/mybatis"/>
                 <property name="username" value="root"/>
                 <property name="password" value="lxn123"/>
             </dataSource>    
         </environment>
     </environments>
     
     <!-- The interface class under the associated package in the configuration file -->
     <mappers>
         <mapper class="com.atguigu.mybatis.test3.UserMapper"/>
     </mappers>
</configuration>
copy code

 

This is an annotation-based method, so create an interface and configure the appropriate annotations on the defined methods. The annotations contain sql statements. It needs to be reminded that this interface does not require a class to implement it.

copy code
package com.atguigu.mybatis.test3;

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.atguigu.mybatis.test.User;

public interface UserMapper {
    
    /*
     * 这是基于注解的映射方式,实现对数据的增删改查,将sql语句直接写在注解的括号中
     * 这是一个接口,其不需要类去实现它
     * 下边分别是插入,删除,修改,查询一个记录,查询所有的记录
     * */
    
    @Insert("insert into users(name,age) values(#{name},#{age})")
    public void insertT(User user);
    
    @Delete("delete from users where id=#{id}")
    public void deleteById(int id);
    
    @Update("update users set name=#{name},age=#{age} where id=#{id}")
    public void updateT(User user);
    
    @Select("select * from users where id=#{id}")
    public User getUser(int id);
    
    @Select("select * from users")
    public List<User> getAllUsers();
}
copy code

 

封装列:User,这儿只写属性,getter和setter,tostring就不写了

private int id;
private String name;
private int age;

 

建立MybatisUtils类,有一个方法,加载mybatis和构建sqlSession

copy code
package com.atguigu.mybatis.test;

import java.io.InputStream;

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

public class MybatisUtils {
    public static SqlSessionFactory getFactory(){
        String resource="conf.xml";
        
        //加载mybatis 的配置文件(它也加载关联的映射文件)
        InputStream is=MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
        
        //构建sqlSession 的工厂
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
        return factory;
    }
}
copy code

 

实现增删改查的方法

copy code
package com.atguigu.mybatis.test3;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import com.atguigu.mybatis.test.MybatisUtils;
import com.atguigu.mybatis.test.User;

public class UserMapperTest {
    
    @Test
    //插入数据
    public void testInsert(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        //使用反射的方法
        UserMapper mapper=session.getMapper(UserMapper.class);
        mapper.insertT(new User(-1, "p", 4));
        
        session.close();
    }
    
    @Test
    //删除数据
    public void testDelete(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        mapper.deleteById(1);
        session.close();
    }
    
    @Test
    //修改数据
    public void testUpdate(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        mapper.updateT(new User(2, "jjjjj", 232));
        session.close();
    }
    
    @Test
    //获取一条数据
    public void testGetUser(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        User user=mapper.getUser(2);
        session.close();
        System.out.println(user);
    }
    
    @Test
    //获取所有数据
    public void testGetAllUsers(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        List<User> users=mapper.getAllUsers();
        
        session.close();
        System.out.println(users);
    }
}
copy code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325992675&siteId=291194637