search
HomeJavajavaTutorialSpring+mabatis for SSM integration in Java development

Spring and mybatis integration

Integration ideas
Spring is required to manage SqlSessionFactory through a singleton.
Spring and myatis integration generate proxy objects and use SqlSessionFactory to create SqlSession. (The integration of spring and mybatis is automatically completed)
The mapper and dao of the persistence layer require spring for management.
Integrate the environment and create a new java project (close to the actual development project structure)
jar package:
jar package of mybatis3.2.7
jar package of spring 4.3.9
mybatis and Spring integration package: Early integration of ibatis and spring is officially provided by spring, and integration of mybatis and spring is provided by mybatis.

sqlSessionFactory

Configure sqlSessionFactory in applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	
	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:db.properties" />
	
	<!-- 数据源,使用dbcp -->        
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"   destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/><!-- jdbc:mysql://localhost:3306/test?characterEncoding=utf8 -->
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>
		<property name="maxActive" value="10"/>
		<property name="maxIdle" value="5"/>
	</bean>

	<!-- sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 加载mybatis的配置文件 -->

		<property name="configLocation" value="mybatis/SqlMapConfig.xml"/>
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource"></property>
		
	</bean>
	<!-- 原始dao接口 -->
 	<bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean> 

</beans>

Original dao development (after integration with spring)

mapper.xml

 <!-- 加载映射文件 -->
 <mappers>
 <mapper resource="sqlmap/User.xml"/>

dao

public interface UserDao {

	//根据id查询用户信息
	public User findUserById(int id)throws Exception;	

dao interface implementation class needs to inject SqlsessionFactory through spring.

Here spring declares the configuration method and configures the dao beans.

Let the UserDaoImpl implementation class inherit the SqlSessionDaoSupport class

	public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao{

        @Override
	public User findUserById(int id) throws Exception {
		//继承SqlSessionDaoSupport ,通过this.getSqlSession()得到sqlSession
		SqlSession sqlSession = this.getSqlSession();
		User user = sqlSession.selectOne("test.findUserById", id);
		//释放资源
		//sqlSession.close();
		return user;
	}
        }

Configure dao

Configure dao in applicationContext.xml.

	<!-- 原始dao接口 -->
 	<bean id="userDao" class="cn.itcast.ssm.dao.UserDaoImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
	</bean>

Run test

public class UserDaoImplTest {
	
	private ApplicationContext applicationContext;
	//在setUp这个方法中得到spring容器
	@Before
	public void setUp()throws Exception{
		applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
		
	}
	
	@Test
	public void testFindUserById() throws Exception {
		UserDao userDao=(UserDao) applicationContext.getBean("userDao");
//		//调用userDao的方法
		User user=userDao.findUserById(1);
		System.out.println(user);
	}

The above is the detailed content of Spring+mabatis for SSM integration in Java development. For more information, please follow other related articles on the PHP Chinese website!

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 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 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

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

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 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 use Java's NIO (New Input/Output) API for non-blocking I/O?How do I use Java's NIO (New Input/Output) API for non-blocking I/O?Mar 11, 2025 pm 05:51 PM

This article explains Java's NIO API for non-blocking I/O, using Selectors and Channels to handle multiple connections efficiently with a single thread. It details the process, benefits (scalability, performance), and potential pitfalls (complexity,

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 use Java's sockets API for network communication?How do I use Java's sockets API for network communication?Mar 11, 2025 pm 05:53 PM

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i

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
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment