编程知识 cdmana.com

Mybatis advanced annotation development

Introduction to common notes

In addition to using the mapping profile to operate , You can also use annotations to manipulate

Commonly used annotations

@Select(” Of the query SQL sentence “): Execute query operation annotation

@Insert(” Newly added SQL sentence “): Execute the new operation annotation

@Update(” Modified SQL sentence “): Perform the modified action notes

@Delete(” Delete the SQL sentence “): Perform the delete operation

Annotation implements query operation

Create interfaces and query methods

Configure the mapping relationship in the core configuration file

Writing test classes

The annotation implements the new operation

Create new method

Writing test classes

Annotations implement modification operations

Create modification methods

Writing test classes

The annotation implements the deletion operation

Create delete method

Writing test classes

 

 StudentMapper

package com.itheima.mapper;

import com.itheima.bean.Student;
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 java.util.List;

public interface StudentMapper {
    // Query all 
    @Select("select * from Student")
    public abstract List<Student> selectAll();
    // New operation 
    @Insert("insert into Student values(#{id},#{name},#{age})")
    public abstract Integer insert(Student stu);
    // Modify the operating 
    @Update("update Student set name=#{name},age=#{age} where id=#{id}")
    public abstract Integer update(Student stu);
    // Delete operation 
    @Delete("delete from Student where id=#{id}")
    public abstract Integer delete(Integer id);
}

  Test01

package com.itheima.test;

import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Test01 {
       @Test
    public void selectAll() throws Exception {
        //1. Add to the core profile 
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2. obtain SqlSession Factory object 
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3. Get... Through factory objects SqlSession object 
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4. obtain StudentMapper Implementation class object of interface 
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5. Call the method in the implementation class object , Accept the results 
        List<Student> list = mapper.selectAll();

        //6. Processing results 
        for (Student student : list) {
            System.out.println(student);
        }

        //7. Release resources 
        sqlSession.close();
        is.close();
    }
    @Test
    public void insert() throws Exception {
        //1. Add to the core profile 
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2. obtain SqlSession Factory object 
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3. Get... Through factory objects SqlSession object 
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4. obtain StudentMapper Implementation class object of interface 
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5. Call the method in the implementation class object , Accept the results 
        Student stu=new Student(9," king 10",30);
        Integer insert = mapper.insert(stu);

        //6. Processing results 
        System.out.println(insert);

        //7. Release resources 
        sqlSession.close();
        is.close();
    }
    @Test
    public void update() throws Exception {
        //1. Add to the core profile 
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2. obtain SqlSession Factory object 
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3. Get... Through factory objects SqlSession object 
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4. obtain StudentMapper Implementation class object of interface 
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5. Call the method in the implementation class object , Accept the results 
        Student stu=new Student(9," king 11",40);
        Integer update = mapper.update(stu);

        //6. Processing results 
        System.out.println(update);

        //7. Release resources 
        sqlSession.close();
        is.close();
    }
    @Test
    public void delete() throws Exception {
        //1. Add to the core profile 
        InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");

        //2. obtain SqlSession Factory object 
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        //3. Get... Through factory objects SqlSession object 
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //4. obtain StudentMapper Implementation class object of interface 
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //5. Call the method in the implementation class object , Accept the results 
        Integer delete = mapper.delete(9);

        //6. Processing results 
        System.out.println(delete);

        //7. Release resources 
        sqlSession.close();
        is.close();
    }
}

  MyBatisConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!--MyBatis Of DTD constraint -->
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<!--configuration  The core root tag -->
<configuration>

    <!-- Introduce the configuration file of the database connection -->
    <properties resource="jdbc.properties"/>

    <!-- To configure LOG4J-->
    <settings>
        <setting name="logImpl" value="log4j"/>
    </settings>

    <!-- names -->
    <typeAliases>
        <package name="com.itheima.bean"/>
    </typeAliases>

    <!--environments Configure the database environment , There can be multiple environments .default Property specifies which -->
    <environments default="mysql">
        <!--environment Configure the database environment   id Property uniquely identifies -->
        <environment id="mysql">
            <!-- transactionManager Business management .  type attribute , use JDBC Default transaction -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- dataSource Data source information    type attribute   Connection pool -->
            <dataSource type="POOLED">
                <!-- property Get the configuration information of the database connection  -->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <!-- Configure mapping relationships -->
    <mappers>
        <package name="com.itheima.mapper"/>
    </mappers>

</configuration>

  log4j.properties

# Global logging configuration
# ERROR WARN INFO DEBUG
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.23.129:3306/db3
username=root
password=root

   Summary of annotation development

Annotations can simplify development operations , Omit the writing of the mapping configuration file .

Commonly used annotations

@Select(” Of the query SQL sentence “): Execute query operation annotation

@Insert(” Newly added SQL sentence “): Execute the new operation annotation

@Update(” Modified SQL sentence “): Perform the modified action notes

@Delete(” Delete the SQL sentence “): Perform the delete operation

Configure mapping relationships

<mappers>

  <package name=" Interface package "/>

</mappers>

 

版权声明
本文为[Star dream tears]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/05/20210524214634226f.html

Scroll to Top