search
HomeJavajavaTutorialGetting Started with MyBatis (6)---Integration of mybatis and spring

1. Integration needs

1.1, method

The data in the previous chapter

requires sPRing to manage SqlsessionFactory through a singleton

spring and mybatis integration generate proxy objects, use SqlSessionFactory to create SqlSession

(spring and mybatis integration automatically Completed)

The mappers of the persistence layer need to be managed by spring

2. Create project integration environment

2.1, create project

Getting Started with MyBatis (6)---Integration of mybatis and spring

2.2, data

db.properties

#database configuration information
#driver
driverClass=com.MySQL.jdbc.Driver
#Connection url
jdbcUrl=jdbc:mysql://localhost:3306/mybatis?character=utf8#Username
user=root
#Password
passWord=root
#Connection pool The minimum number of connections reserved in
minPoolSize=10#The maximum number of connections reserved in the connection pool. Default: 15 maxPoolSize=20#Maximum idle time, the connection will be discarded if it is not used within 1800 seconds. If it is 0, it will never be discarded. Default: 0 maxIdletime=1800#The number of connections c3p0 obtains at the same time when the connections in the connection pool are exhausted. Default: 3acquireIncrement=3#The number of initial connections in the connection pool should be between minPoolSize and maxPoolSize. The default is 3
initialPoolSize=15

2.3, confinguration

br/> PUBLIC "-//mybatis.org //DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">< ;/settings>










2.4 POJO classes and interfaces

package com.pb.ssm.po;import java.util.Date;/**
*

* @ClassName: Author

* @Description: TODO(author)

* @author Liu Nan

* @date 2015-10-31 12:39:33 pm

**/public class Author {    //作者id
   private Integer authorId;    //作者姓名
   private String authorUserName;    //作者密码
   private String authorPassword;    //作者邮箱
   private String authorEmail;    //作者介绍
   private String authroBio;    //注册时间
   private Date registerTime;    
   
   
   public Integer getAuthorId() {        return authorId;
   }    public void setAuthorId(Integer authorId) {        this.authorId = authorId;
   }    public String getAuthorUserName() {        return authorUserName;
   }    public void setAuthorUserName(String authorUserName) {        this.authorUserName = authorUserName;
   }    public String getAuthorPassword() {        return authorPassword;
   }    public void setAuthorPassword(String authorPassword) {        this.authorPassword = authorPassword;
   }    public String getAuthorEmail() {        return authorEmail;
   }    public void setAuthorEmail(String authorEmail) {        this.authorEmail = authorEmail;
   }    public String getAuthroBio() {        return authroBio;
   }    public void setAuthroBio(String authroBio) {        this.authroBio = authroBio;
   }    public Date getRegisterTime() {        return registerTime;
   }    public void setRegisterTime(Date registerTime) {        this.registerTime = registerTime;
   }
   @Override    public String toString() {        return "Author [authorId=" + authorId + ", authorUserName="
               + authorUserName + ", authorPassword=" + authorPassword                + ", authorEmail=" + authorEmail + ", authroBio=" + authroBio                + ", registerTime=" + registerTime + "]";
   }
   
   
}

 

接口

 

package com.pb.ssm.mapper;import com.pb.ssm.po.Author;public interface AuthorMapper { /**
* *

* @Title: findAuthorById

* @Description: TODO (search based on id)

* @param @param id
* @param @return Setting file

* @return Author Return type

* @ throws
*/
public Author findAuthorById(int id);
/**
* *

* @Title: addAuthor

* @Description: TODO(Add)

* @param @param author
* @param @return Setting file

* @return int Return type

* @throws
* /
public int addAuthor(Author author); /**
* *

* @Title: updateAuthor

* @Description: TODO(update)

* @param @param author
* @param @return Setting file

* @return int Return type

* @throws
*/
public int updateAuthor(Author author);
/**
* * Delete

* @Title: delteAuthor

* @Description: TODO (delete by ID)

* @param @param id
* @param @return Setting file

* @return int Return type

* @throws
*/
public int delteAuthor(int id);
}

mapper.xml

br/> PUBLIC "-//mybatis.org//DTD Mapper 3.0/ /EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">INSERT INTO author(author_username, author_password,author_email,author_bio)
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio})
update authorauthor_username=#{authorUserName},author_password=#{authorPassword},author_email=#{authorEmail},author_bio=#{authroBio},register_time=#{registerTime} if>where author_id=#{authorId}delete from author where author_id= #{authorId}

3. Use Mybatis configuration file.xml integration

3.1、写applicationContext.xml



 

3.2、测试

 

package com.pb.ssm.mapper;import java.io.InputStream;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.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.pb.ssm.po.Author;public class AuthorMapperTest {    private ApplicationContext applicationContext;

   @Before    public void setUp() throws Exception {
       applicationContext=new ClassPathXmlApplicationContext("ApplicationContext.xml");
   }

   @Test    public void testFindAuthorById() {
       

       AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
       Author author = authorMapper.findAuthorById(2);
       System.out.println(author);
   
   }

   @Test    public void testAddAuthor() {        // 获取会话工厂
       AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
       
       Author author=new Author();
       author.setAuthorUserName("程序猿");
       author.setAuthorPassword("QWERdlfdad");
       author.setAuthorEmail("QWER@QQ.com");        
       
       int  num = authorMapper.addAuthor(author);
   
       System.out.println("num="+num);
       System.out.println("添加后的ID:"+author.getAuthorId());
   }

   @Test    public void testUpdateAuthor() {        // 获取会话工厂
       AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");
       Author author = authorMapper.findAuthorById(13);
       author.setAuthroBio("天天写代码");
       author.setAuthorUserName("码农");        int num=authorMapper.updateAuthor(author);
   
       System.out.println("num="+num);
       System.out.println(author);
   }

   @Test    public void testDeleteAuthor() {        // 获取会话工厂
       AuthorMapper authorMapper = (AuthorMapper) applicationContext.getBean("authorMapper");        int num= authorMapper.delteAuthor(13);
       
   }

}

 

 

 

四、不使用mybatis配置文件

4.1、写ApplicationContext.xml

 



 

更改Mapper.xml,因为不能使用别名,所以type要写POJO类的全路径

br/>  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">INSERT INTO author(author_username,author_password,author_email,author_bio)
VALUES(#{authorUserName},#{authorPassword},#{authorEmail},#{authroBio})
update authorauthor_username=#{authorUserName},author_password=#{authorPassword},author_email=#{authorEmail},author_bio=#{authroBio},register_time=#{registerTime}where author_id=#{authorId}delete from author where author_id=#{authorId}

 

测试类同上

 以上就是MyBatis入门(六)---mybatis与spring的整合的内容,更多相关内容请关注PHP中文网(www.php.cn)! 


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment