`
随心而行
  • 浏览: 13869 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

spring+mybaits配置

 
阅读更多
本文介绍spring+mybatis配置,数据库使用mysql,mybatis代码使用mybatis-generator生成

1、创建maven项目,加入spring、mybatis、mysql、proxool依赖,并加入mybatis-generator插件,pom.xml如下
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.qerooy</groupId>
	<artifactId>spring-mybatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	
	<properties>
		<spring.version>4.0.2.RELEASE</spring.version>
		<mybatis.version>3.2.2</mybatis.version>
		<mybatis-spring.version>1.2.0</mybatis-spring.version>
		<log4j.version>1.2.17</log4j.version>
		<mysql.version>5.1.29</mysql.version>
		<proxool.version>0.9.1</proxool.version>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>
		
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${mybatis-spring.version}</version>
		</dependency>
		
		<dependency>
			<groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>${mysql.version}</version>
		</dependency>
		
		<dependency>
			<groupId>proxool</groupId>
			<artifactId>proxool</artifactId>
			<version>${proxool.version}</version>
		</dependency>
		
		<dependency>
			<groupId>com.cloudhopper.proxool</groupId>
			<artifactId>proxool-cglib</artifactId>
			<version>${proxool.version}</version>
		</dependency>
		
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>3.2.3.RELEASE</version>
			<scope>test</scope>
		</dependency>
		
	</dependencies>
	
	<build>
		<plugins>
			<plugin>
				<groupId>org.mybatis.generator</groupId>
				<artifactId>mybatis-generator-maven-plugin</artifactId>
				<version>1.3.2</version>  
			</plugin>
		</plugins>
	</build>
</project>


2、创建数据库qerooy,并创建一个user表;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(30) NOT NULL,
  `password` varchar(50) NOT NULL,
  `remark` varchar(50) DEFAULT NULL,
  `create_time` datetime NOT NULL,
  `update_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=utf8;


3、编写mybatis-generator代码生成插件配置文件generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
  <classPathEntry location="D:\.m2\repository\mysql\mysql-connector-java\5.1.29\mysql-connector-java-5.1.29.jar" />

  <context id="Mysql2Tables" targetRuntime="MyBatis3">
  
  	<plugin type="org.mybatis.generator.plugins.RowBoundsPlugin">
  	</plugin>
  	 
	<commentGenerator>
		<property name="suppressAllComments" value="false" />
		<property name="suppressDate" value="true" />
	</commentGenerator>
    
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/qerooy"
        userId="root"
        password="123jkl">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <javaModelGenerator targetPackage="com.qerooy.model" targetProject="src/main/java">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="map"  targetProject="src/main/resources/">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.qerooy.mapper"  targetProject="src/main/java">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>
    
    <table schema="root" tableName="user" domainObjectName="User" >
    	<generatedKey column="id" sqlStatement="MYSQL" identity="true" />
    </table>
 
  </context>
</generatorConfiguration>



执行命令 mvn -Dmybatis.generator.overwrite=true mybatis-generator:generate生成mybatis代码

4、编写mybatis分页插件
package com.qerooy.base.dialect;

public class Dialect {

	public boolean supportsLimit() {
		return false;
	}

	public boolean supportsLimitOffset() {
		return supportsLimit();
	}

	public String getLimitString(String sql, int offset, int limit) {
		return getLimitString(sql, offset, Integer.toString(offset), limit, Integer.toString(limit));
	}

	public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
		throw new UnsupportedOperationException("paged queries not supported");
	}

}


package com.qerooy.base.dialect;

public class Dialect {

	public boolean supportsLimit() {
		return false;
	}

	public boolean supportsLimitOffset() {
		return supportsLimit();
	}

	public String getLimitString(String sql, int offset, int limit) {
		return getLimitString(sql, offset, Integer.toString(offset), limit, Integer.toString(limit));
	}

	public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
		throw new UnsupportedOperationException("paged queries not supported");
	}

}


package com.qerooy.base.dialect;

public class Dialect {

	public boolean supportsLimit() {
		return false;
	}

	public boolean supportsLimitOffset() {
		return supportsLimit();
	}

	public String getLimitString(String sql, int offset, int limit) {
		return getLimitString(sql, offset, Integer.toString(offset), limit, Integer.toString(limit));
	}

	public String getLimitString(String sql, int offset, String offsetPlaceholder, int limit, String limitPlaceholder) {
		throw new UnsupportedOperationException("paged queries not supported");
	}

}


5、编写spring配置文件applicationContext.xml、jdbc.properties
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd  
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<context:component-scan base-package="*" />
	
	<util:properties id="dataSourceProps" location="classpath:jdbc.properties" />

	<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">
		<property name="driver" value="#{dataSourceProps['jdbc.driverClassName']}" />
		<property name="driverUrl" value="#{dataSourceProps['jdbc.url']}" />
		<property name="user" value="#{dataSourceProps['jdbc.username']}" />
		<property name="password" value="#{dataSourceProps['jdbc.password']}" />
	</bean>

	<!-- 配置Mybatis -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="mapperLocations" value="classpath:map/*.xml" />
		<property name="plugins">
			<list>
				<ref bean="pagingPlugin" />
			</list>
		</property>
	</bean>

	<bean id="pagingPlugin" class="com.qerooy.base.plugin.PagingPlugin">
		<property name="dialectClass">
			<value>#{dataSourceProps['jdbc.dialect']}</value>
		</property>
	</bean>

	<bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.qerooy.mapper" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>

</beans>

jdbc.username=root
jdbc.password=123jkl
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/qerooy?useUnicode=true&characterEncoding=UTF-8
jdbc.dialect=com.qerooy.base.dialect.MySQLDialect
jdbc.initialPoolSize=10
jdbc.minPoolSize=2
jdbc.maxPoolSize=5
jdbc.maxIdleTime=60
jdbc.acquireIncrement=5
jdbc.idleConnectionTestPeriod=60
jdbc.acquireRetryAttempts=20
jdbc.breakAfterAcquireFailure=true
jdbc.maxStatements=0
jdbc.testConnectionOnCheckout=false


6、编写Service操作数据库类及测试代码
package com.qerooy.service;

import java.util.List;

import org.apache.ibatis.session.RowBounds;

import com.qerooy.model.User;
import com.qerooy.model.UserExample;

public interface UserService {

	public User findById(Integer id);
	
	public List<User> findByPage(UserExample example,RowBounds rowBounds);
	
}


package com.qerooy.service.impl;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qerooy.mapper.UserMapper;
import com.qerooy.model.User;
import com.qerooy.model.UserExample;
import com.qerooy.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	UserMapper userMapper;
	
	@Override
	public User findById(Integer id) {
		return userMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public List<User> findByPage(UserExample example,RowBounds rowBounds){
		return userMapper.selectByExampleWithRowbounds(example,rowBounds);
	}

}


package com.qerooy;

import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.qerooy.model.User;
import com.qerooy.model.UserExample;
import com.qerooy.service.UserService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:applicationContext*.xml"}) 
public class MybatisTest {
	
	@Autowired
	UserService userService;

	@Test
	public void findById() {
		User user = userService.findById(3);
		System.out.println(user);
	}
	
	@Test
	public void findByPage() {
		UserExample example = new UserExample();
		RowBounds rowBounds = new RowBounds(1,10);
		List<User> list = userService.findByPage(example,rowBounds);
		System.out.println(list);
	}

}



为方便查看sql语句,可配置以下log4j.properties
log4j.rootCategory=INFO, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=[%p] %c %m%n

log4j.logger.com.qerooy.mapper = DEBUG

分享到:
评论

相关推荐

    spring+spring mvc+mybaits搭建基础框架

    spring+spring mvc+mybaits搭建基础框架,内集成sqllite数据库,直接把demo中的war包放到服务器下即可运行,实现数据库密码连接等信息在配置文件中以密文形式存在des方式加密解密,。http://localhost:8090/

    springmvc+spring+mybaits的整合

    springmvc+spring+mybaits的简单整合和相关配置、

    Struts2+Spring+Mybaits3框架整合实例

    2. 配置Spring:定义ApplicationContext,配置Bean,开启注解扫描。 3. 配置MyBatis3:配置SqlSessionFactory,创建Mapper接口,使用注解编写SQL。 4. 整合Struts2和Spring:通过Struts2的Spring插件,使Action类...

    springmvc+mybaits配置示例

    例如,`testmvc` 文件可能包含了一个简单的 Spring MVC 项目,其中包含了配置文件、Controller、Service 和 MyBatis 相关的配置及映射文件。通过这样的组合,开发者可以快速构建出功能完备的 Web 应用。

    springMvc+spring+activeMq+mybaits

    在IT行业中,构建高效、可扩展的Web应用是至关重要的,而"springMvc+spring+activeMq+mybaits"这个项目组合提供了一个强大的框架基础。本文将深入探讨这四个关键技术及其相互间的协同工作。 首先,Spring MVC是...

    spring+mybaits整合

    3. 集成Spring:在Spring的配置文件(如applicationContext.xml)中,引入MyBatis的配置,并声明SqlSessionFactory和MapperScannerConfigurer bean,后者会自动扫描指定包下的Mapper接口。 4. 创建Mapper接口:定义...

    springmvc+mybaits+spring

    【标题】"springmvc+mybaits+spring"是一个典型的Java Web开发框架组合,用于构建高效、可维护的Web应用程序。这个源码示例涵盖了MyBatis、Spring MVC和Spring这三个核心组件,它们各自承担着不同的职责。 【描述】...

    springboot+mybaits+html+mysql简单demo

    - **Spring Boot Starter**:预定义的依赖集合,简化配置。 2. **MyBatis简介** - MyBatis是一个轻量级的持久层框架,它解决了JDBC的繁琐配置和SQL的编写问题。 - **Mapper接口**:提供了面向接口编程的方式,将...

    Springmvc+mybaits+mysql的Demo源码

    1. **配置文件**:包括Spring的配置文件(如`applicationContext.xml`),MyBatis的配置文件(如`mybatis-config.xml`),以及数据库连接相关的配置(如`db.properties`)。 2. **实体类(Entity)**:这些类代表...

    SpringMVC+Mybaits+Spring+MySQL实现登录注册Demo

    1. **配置文件**:包括 `spring-context.xml`(Spring 配置)、`mybatis-config.xml`(MyBatis 配置)以及 `web.xml`(Web 应用配置)。这些文件定义了框架间的连接和配置,如数据源、事务管理器、扫描的包路径等。 ...

    SSM(spring+springMVC+mybaits)整合框架

    1. **配置Spring**:首先,我们需要配置Spring的IoC容器,声明Bean的定义,包括SpringMVC的DispatcherServlet、Controller、Service、DAO等。此外,还需要配置数据源和事务管理器,以便Spring能够管理和控制事务。 ...

    使用springMVC+spring+mybaits 整合源码(mybatis 自动生成)

    接着,配置Spring的`applicationContext.xml`,包括数据源、事务管理器、MyBatis的SqlSessionFactory和MapperScannerConfigurer。然后,配置Spring MVC的`servlet-context.xml`,设置视图解析器、拦截器和处理器映射...

    springboot+security+jwt+mybaits-plus+mysql实现权限管理

    1. Spring Boot:Spring Boot是Spring框架的一个简化版,它通过预配置的starter依赖项和自动配置功能,使得开发人员能够快速搭建应用程序。在这个项目中,Spring Boot作为基础框架,负责应用的初始化、依赖管理和...

    Spring+SpringMVC+Mybaits整合jar包

    综上所述,"Spring+SpringMVC+Mybaits整合jar包"是将这三个框架的最新版本(spring4.3.9, springmvc4.3.9, mybatis3.4.4)打包在一起,提供了一个完整的依赖环境,便于开发者快速搭建SSM项目,节省配置时间,提高...

    maven+spring+springMvc+mybaits+freemarker

    这个项目中,开发者已经搭建了一个基本的Web应用框架,包括了所有必要的配置和初始化设置。SQL脚本可能是用来初始化数据库的,包含创建表、插入数据等操作。这使得其他人可以直接使用此项目作为基础,快速开发自己的...

    spring4+springMVC+mybaits3

    标题 "spring4+springMVC+mybaits3" 提示我们关注的是Spring框架的第四版(Spring 4)与Spring MVC以及MyBatis 3的整合应用。这是一个常见的Java Web开发技术栈,用于构建高效、灵活且可扩展的企业级应用程序。 ...

    ssi框架整合 struts+spring+mybaits 简单示例

    - **Spring配置**:首先,我们需要配置Spring的ApplicationContext,定义Bean并注入依赖,包括Struts的Action类、Service层接口及其实现、MyBatis的SqlSessionFactory等。 - **Struts配置**:在struts.xml中定义...

    个人博客 springmvc + spring +mybaits 的框架.zip

    - src/main/resources:存放配置文件,如Spring的bean配置、MyBatis的映射文件等。 - src/main/webapp:Web应用的根目录,包含静态资源(如CSS、JavaScript)、视图(JSP或HTML)以及WEB-INF下的web.xml配置文件。 -...

    spring+mybaits测试可以用

    2. **Spring MVC配置文件**:如`servlet-context.xml`,配置前端控制器DispatcherServlet、视图解析器、拦截器等。 3. **MyBatis配置文件**:`mybatis-config.xml`,包含MyBatis的全局配置,比如数据源、事务管理器...

Global site tag (gtag.js) - Google Analytics