Spring framework and mybatis framework are integrated to solve the problem

Time:2021-12-2

1. Title Description

Spring framework and mybatis framework are integrated to solve the problem

2. Reference solution

Bookcontroller.java under com.controller package

package com.controller;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.dao.BookDao;
import com.po.MyBook;
@Controller("bookController")
public class BookController {
    @Autowired
    private BookDao bookDao;
    public void test() {
        //Query a book record
        MyBook abook = bookDao.selectBookBySN(1);
        System.out.println(abook);
        System.out.println("================");
        //Add a book record
        MyBook addmb = new MyBook();
        Addmb.setbookname ("journey to the west");
        addmb.setBookPrice((float) 24.6);
        int add = bookDao.addBook(addmb);
        System.out.println ("added" + add + "records");
        System.out.println("================");
        //Modify a book record
        MyBook updatemb = new MyBook();
        updatemb.setSn(1);
        Updatemb.setbookname ("dream of Red Mansions");
        updatemb.setBookPrice((float) 35.3);
        int up = bookDao.updateBook(updatemb);
        System.out.println ("modified" + up + "records");
        System.out.println( "================");
        //Delete a book record
        int dl = bookDao.deleteBook(9);
        System.out.println ("deleted" + DL + "records");
        System.out.println("================");
        //Query all book records
        List<MyBook> list = bookDao.selectAllBook();
        for (MyBook myBook : list) {
            System.out.println(myBook);
        }
    }
}

Testcontroller.java under com.controller package

package com.controller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestController {
    public static void main(String[] args) {
        ApplicationContext appCon = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookController bc = (BookController)appCon.getBean("bookController");
        bc.test();
    }
}

Bookdao.java under com.dao package

package com.dao;
import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import com.po.MyBook;
@Repository("bookDao")
@Mapper
/*Use spring to automatically scan the interface of mybatis and assemble it
(spring automatically assembles all interfaces marked by @ mapper annotation in the specified package as the mapping interface of mybatis*/
public interface BookDao {
    /**
     *The interface method corresponds to the ID in the SQL mapping file usermapper.xml
     */
    public MyBook selectBookBySN(Integer sn);
    public List<MyBook> selectAllBook();
    public int addBook(MyBook book);
    public int updateBook(MyBook book);
    public int deleteBook(Integer sn);
}

Bookmapper.xml under com.mybatis package

<?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="com.dao.BookDao">
    <!--  Query book records according to Sn -- >
    <select id="selectBookBySN" parameterType="Integer" 
        resultType="com.po.MyBook">
        select * from book where sn=#{sn}
    </select>
    <!--  Query all book information -- >
    <select id="selectAllBook"  resultType="com.po.MyBook">
        select * from book
    </select>
    <!--  Add a book record, #{bookname} as the attribute value of com.po.mybook -- >
    <insert id="addBook" parameterType="com.po.MyBook">
        insert into book (bookName,bookPrice) values(#{bookName},#{bookPrice})
    </insert>
    <!--  Modify a book record -- >
    <update id="updateBook" parameterType="com.po.MyBook">
        update book set bookName = #{bookName},bookPrice = #{bookPrice} where sn=#{sn}
    </update>
    <!--  Delete a book record -- >
    <delete id="deleteBook" parameterType="Integer"> 
        delete from book where sn=#{sn}
    </delete>
</mapper>

Mybatis-config.xml under com.mybatis package

<?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>
    <!--  Tell mybatis where to find the mapping file -- >
     <mappers>
        <mapper resource="com/mybatis/BookMapper.xml"/>
     </mappers>
</configuration>

Bookmapper.xml under com.mybatis.mapper package

<?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="com.dao.UserDao">
    <!--  Query book records according to Sn -- >
    <select id="selectBookBySN" parameterType="Integer" 
        resultType="com.po.MyBook">
        select * from book where sn = #{sn}
    </select>
    <!--  Query all book information -- >
    <select id="selectAllBook"  resultType="com.po.MyBook">
        select * from book
    </select>
    <!--  Add a book record, #{bookname} as the attribute value of com.po.mybook -- >
    <insert id="addBook" parameterType="com.po.MyBook">
        insert into book (bookName,bookPrice) values(#{bookName},#{bookPrice})
    </insert>
    <!--  Modify a book record -- >
    <update id="updateBook" parameterType="com.po.MyBook">
        update book set bookName = #{bookName},bookPrice = #{bookPrice} where sn = #{sn}
    </update>
    <!--  Delete a book record -- >
    <delete id="deleteBook" parameterType="Integer"> 
        delete from user where sn = #{sn}
    </delete>
</mapper>

Mybook.java under package com.mybatis.po

package com.mybatis.po;
/**
 *Persistence class of book table in springtest database
 */
public class MyBook {
    private Integer sn;// Primary key
    private String bookName;
    private Float  bookPrice;
    public Integer getSn() {
        return sn;
    }
    public void setSn(Integer sn) {
        this.sn = sn;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public Float getBookPrice() {
        return bookPrice;
    }
    public void setBookPrice(Float bookPrice) {
        this.bookPrice = bookPrice;
    }
    @Override
    public String toString() {
        return "MyBook [sn=" + sn + ", bookName=" + bookName + ", bookPrice=" + bookPrice + "]";
    }
}

Mybatistest.java under com.mybatis.test package

package com.mybatis.test;
import java.io.IOException;
import java.io.InputStream;
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 com.mybatis.po.MyBook;

public class MyBatisTest {
    public static void main(String[] args) {
        try {
            //Read the configuration file mybatis-config.xml
            InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
            //Build sqlsessionfactory from configuration file
            SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
            //Create sqlsession through sqlsessionfactory
            SqlSession ss = ssf.openSession();
            //Sqlsession executes the SQL defined in the mapping file and returns the mapping result
            //Com.mybatis.mapper.usermapper.selectuserbyid is the ID of namespace + select in usermapper.xml
            //Query a book record
            MyBook mb = ss.selectOne("com.mybatis.mapper.BookMapper.selectBookBySN", 1);
            System.out.println(mb);
            //Add a book record
            MyBook addmb = new MyBook();
            addmb.setSn(24);
            Addmb.setbookname ("Romance of the Three Kingdoms");
            addmb.setBookPrice((float) 50.2);
            ss.insert("com.mybatis.mapper.BookMapper.addBook",addmb);
            //Modify a book record 
            MyBook updatemb = new MyBook();
            updatemb.setSn(1);
            Updatemb.setbookname ("outlaws of the marsh");
            updatemb.setBookPrice((float) 40.1);
            ss.update("com.mybatis.mapper.BookMapper.updateBook", updatemb);
            //Delete a book record
            ss.delete("com.mybatis.mapper.BookMapper.deleteBook", 3);
            //Query all book records
            List<MyBook> listMb = ss.selectList("com.mybatis.mapper.BookMapper.selectAllBook");
            for (MyBook myBook : listMb) {
                System.out.println(myBook);
            }
            //Commit transaction
            ss.commit();
            //Close sqlsession
            ss.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Mybook.java under com.po package

package com.po;
/**
 *Persistence class of book table in springtest database
 */
public class MyBook {
    private Integer sn;// Primary key
    private String bookName;
    private Float  bookPrice;
    
    public Integer getSn() {
        return sn;
    }
    public void setSn(Integer sn) {
        this.sn = sn;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public Float getBookPrice() {
        return bookPrice;
    }
    public void setBookPrice(Float bookPrice) {
        this.bookPrice = bookPrice;
    }
    
    @Override
    public String toString() {
        return "MyBook [sn=" + sn + ", bookName=" + bookName + ", bookPrice=" + bookPrice + "]";
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--  Specify the packages (including sub packages) to be scanned to make the annotation effective -- >
    <context:component-scan base-package="com.dao"/>
    <context:component-scan base-package="com.controller"/>
    <!--  Configure data source -- >
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/springtest?characterEncoding=utf8&amp;useSSL=false"/>
            <property name="username" value="root" />
            <property name="password" value="123456" />
            <!--  Maximum connections -- >
            <property name="maxTotal" value="30"/>
            <!--  Maximum free connections -- >
            <property name="maxIdle" value="10"/>
            <!--  Number of initialized connections -- >
            <property name="initialSize" value="5"/>
    </bean>
    <!--  Add transaction support -- >
    <bean id="txManager"   
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
        <property name="dataSource" ref="dataSource" />   
    </bean> 
    <!--  Open transaction annotation -- >
    <tx:annotation-driven transaction-manager="txManager" />
     <!--  Configure the mybatis factory, specify the data source, and integrate perfectly with mybatis -- >  
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!--  The attribute value of configlocation is the core configuration file of mybatis -- >
        <property name="configLocation" value="classpath:com/mybatis/mybatis-config.xml"/>
    </bean>  
    <!-- Mapper agent development, using spring to automatically scan and assemble the interface of mybatis
     (spring automatically assembles all interfaces marked by @ mapper annotation in the specified package as the mapping interface of mybatis) - > 
     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
         <!--  Scanner for mybatis spring component -- >
         <property name="basePackage" value="com.dao"/>
         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
     </bean>
</beans>

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.dao=DEBUG
# 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