(A) Mybatis basic configuration, Statement embodiment, the dynamic proxy CRUD

First, understand Mybatis is doing, before using jdbc to operate the database a lot of time to write statements to get the cursor, connection, access to specific objects corresponding operation, code is too complicated, so now have Mybatis, this operation will integrate together, you between and do not care about the specific database interaction, you now just need to take care of your business logic, good writing your sql statement and the corresponding configuration on it, thereby greatly enhancing the development efficiency, simplify unnecessary code. ps: To be honest I really feel cumbersome jdbc operation, should pay attention too much, much more convenient this way to operate the database, after all, it is our most important business logic code.

This blog records the CRUD basic configuration, statement mode, dynamic proxy approach

Mybatis basic configuration

1. First, we start with the official website of the compressed package downloaded, then the .jar files in the directory introduction into the project file, under Intellij, the introduction of the jar file, ask specifically how the introduction of the mother, pay attention here only temporarily need to introduce a .jar files, jar files in the lib directory is equivalent to extensions, when you need reintroduction. Then the same manner jdbc introducing it because Mybatis is dependent on the jdbc, jdbc is understood to be a package.

2. Next we create good config.xml file for connection configuration database, as follows

<?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">  <!--默认的配置环境,发行版本,debug版本-->
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">   <!--创建连接池,效率高,一次打开,多次使用-->
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>   
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT"/>
                <property name="username" value="xxx"/>
                <property name="password" value="XXXX " /> 
            </ the dataSource> 
        </ Environment> 
    </ Environments> 
    <by mappers> 
        <-! a load map file, a plurality of direct write path with respect to the file src -> 
        <Resource Mapper = " Entity / PersonMapping .xml " /> 
    </ by mappers> 
</ Configuration>

Look at it this xml file, it is quite easy to understand, pay attention to two points,

1. I used here is the mysql 8.0.2 version, mysql configuration and low versions are not the same, is behind the url parameter & amp; be separated. Although not known for this spread, anyway, so the provisions of the people.

2. When the lowermost <mappers> load map file, a <mapper resource- "xxx" /> a load, is a specific attribute mapping Resource file relative to the src file.

Next we create a Person class, and a mapping table in the database form: as follows

package entity;
public class Person {
   private int id;
private String name; private String loves; public Person(){ }
  
public Person(String name, String loves) { this.name = name; this.loves = loves; }
  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 String getLoves() { return loves; } public void setLoves(String loves) { this.loves = loves; } public String toString(){ return "姓名:"+this.name+"\n爱好:"+this.loves; } }

TABLE person as follows:

 create table person(
     `id` int(11) not null auto_increment primary key,
     `name` varchar(30) not null,
     loves varchar(40) not null
     )engine=innodb;

 

然后看映射文件 PersonMapping.xml的配置,这个映射文件和Person类时对应的,配置的是关于表person和类Person的相关操作

<?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="entity.PersonMapping">        <!--该mapping文件的唯一映射-->
    <select id="selectPersonById" resultType="entity.Person" parameterType="string">
        select * from person where `name` = #{name}
    </select>
    <insert id="insertOnePerson" parameterType="entity.Person">
        insert into person values(#{name},#{loves})
    </insert>
    <delete id="deleteOnePerson" parameterType="int" >
        delete from person where id=#{id}
    </delete>
</mapper>

可以看到首先namespace是该文件一个唯一标识,就是该文件的路径(相对于src),接下来有各种标签,<select>  <delete>  <insert> ..这其实就对应了数据库的增删改查,具体对哪一张表,什么操作,看你书写的sql语句,因为我们看到标签体的内容就是sql语句,举个例子:

    <insert id="insertOnePerson" parameterType="entity.Person" resultType="">
        insert into person values(#{name},#{loves})
    </insert>

这个标签是向数据库插入数据,id代表的是该sql语句的唯一标识,parameterType  指的是传入的参数类型,这里是entity.Person,Person使我们构造的一个类,resultType是返回值的类型,

标签体是我们书写的sql语句,这里是动态传值的方式,输出格式是:#{变量名},对于变量名我们注意:如果传入的是一个string,int等类型的数据,那这个变量名可以是任何字符,但是如果传入的是一个对象的话,那么变量名就必须和该对象的属性一一对应起来,比如  name  就指 person对象的name属性,loves指person的loves属性。另外注意Mybatis传参只能传一个值,但是有时候要传多个参数,可以使用数组的方式传值。

同样的,增删改查操作都是在相应的标签下书写sql语句来完成的。

statement的增删改查

到这里我们的基本配置demo就算是完成了,接下来写一个具体的操作例子,首先分为三步:

1.加载配置信息,2.获取SqlSession对象进行操作  3.执行指定的sql语句

    public static void main(String[] args) throws IOException {
        //加载配置信息
        Reader reader = Resources.getResourceAsReader("config.xml");
        //connection
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = sessionFactory.openSession();
        //执行指定的sql语句
        String statement = "entity.PersonMapping.selectPersonById";  //查询数据
        List<Person> persons = new ArrayList<Person>(sqlSession.selectList(statement,"温鸿飞"));
        for (Person person:persons) {
            System.out.println(person.toString());
        }
        statement = "entity.PersonMapping.deleteOnePerson";   //删除数据
        sqlSession.delete(statement,1);
        System.out.println("------");
        statement = "entity.PersonMapping.selectPersonById";   //查询数据
        persons = new ArrayList<Person>(sqlSession.selectList(statement,"温鸿飞"));
        for (Person person:persons) {
            System.out.println(person.toString());
        }
        sqlSession.commit();
        sqlSession.close();
    }

配置信息加载是通过Reader reader = Resources.getResourceAsReader("config.xml"); 完成,config就是我们刚才创建的配置文件,告诉编译器都有哪些mapper,

获取SqlSession对象,这个不说了,官网就是这么写的,规定

然后到了具体的操作了,看到我们先书写了一个 statement,这个statement对应了刚才的PersonMapping.xml文件当中的一个标签,格式是:namespace.id,比如

entity.PersonMapping.deleteOnePerson指的就是deleteOnePerson的标签,之后用SqlSession来操作,调用增删改查里面的一个方式,传入statement和相应的参数就可以了,比如删除
SqlSession.delete(statement,param); 之后有返回值的接受一下, 没有就算了。sqlSession.commit()提交一下事务,当然这里还有回滚等暂时不说了
上面的代码执行结果如下,可以看到正确的查询到了数据并删除了id为1 的数据
"C:\Program Files\Java\jdk-11.0.1\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=63824:C:\Program Files\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath C:\learn\java\mybatis\out\production\mybatis;C:\迅雷下载\mybatis-3.5.2\mybatis-3.5.2\mybatis-3.5.2.jar;C:\迅雷下载\mysql-connector-java-8.0.16.jar entity.test
姓名:温鸿飞
爱好:哈啊哈哈
姓名:温鸿飞
爱好:21212121
姓名:温鸿飞
爱好:2121266
------
姓名:温鸿飞
爱好:21212121
姓名:温鸿飞
爱好:2121266

到这里我们的第一个statement小demo就算成功完成了,但使用statement的话,每次都要书写statement,很繁琐,所以我们有了动态的进行增删改查的方式,其实就是将statemtn语句进行约定,名字什么都是有固定规则的,简化代码,省略掉statement,简单来讲,让约定优于配置,根据约定定位sql语句

具体的话,看下面:

定义一个接口,通过这个接口来替代statement,该接口有如下规则;

1.接口名和映射.xml文件的文件名相同

2.接口之中的抽象方法的方法名,返回值,参数和映射.xml之中配置的均相同,

3.注意一下如果要返回一个数组的话,使用  List<className> 作为返回类型

定义好了之后通过SqlSession.getMapper(接口名字.class);来获取到操作数据库的对象,之后调用该接口的方法就可以了,具体代码如下:

PersonMapping接口

package mappers;
import entity.Person;

import java.util.List;

//操作person类的接口
public interface PersonMapping {    //接口名也一样
    public abstract Person selectPersonById(int id);  //方法名,返回值,参数均和配置一样
    void deletePersonById(int id);
    void insertOnePerson(Person person);
    public abstract List<Person> selectPersonByName(String name);
}

main函数之中:

public class test {
    public static void main(String[] args) throws IOException {
        //加载配置信息
       。。。获取到SqlSession对象,和前面一样//获取到mapper对象
        PersonMapping personMapping = sqlSession.getMapper(PersonMapping.class);
        //调用接口方法操作数据库
        Person person = personMapping.selectPersonById(2);
        System.out.println(person);
        List<Person> persons = personMapping.selectPersonByName("温鸿飞");
        for (Person temp:persons) {
            System.out.println(temp);
        }
        sqlSession.commit();
        sqlSession.close();
    }
}

感觉这和symfony里面的Respository一样呀,不过你这个还要自己配置,Symfonyh都自己配置好了,你直接实例化对象就行了,symfony很强呀

 

Guess you like

Origin www.cnblogs.com/eenio/p/11314611.html