mybatis教程:使用spring+mybatis做添查改删,mybatisspring,mybatis是ibat
mybatis教程:使用spring+mybatis做添查改删,mybatisspring,mybatis是ibat
mybatis是ibatis的升级版本,也是通过写sql来操作数据库,它比ibatis使用更便捷,在ibatis中我们需要对每个方法都手动调用执行指定的sqlId,而在mybatis中我们只需要定义出对数据表操作的接口,并写出这些操作的sql配置就可以了。
下面我们看一个真实的示例,我们要操作的表是todo表,其结构如下ddl定义;
delimiter $$CREATE TABLE `todo` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(200) NOT NULL, `createTime` datetime NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8$$
这张表非常简单,只有三个字段,id是自增长的主键,title是varchar类型的,createTime是记录的创建时间。
我们看下使用mybatis操作这张数据表的步骤:
首先新建一个maven项目,在pom.xml中添加如下依赖项:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.0.1</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.25</version> </dependency>
三个依赖中mybatis-spring是mybatis对spring的集成的jar包,commons-dbcp是数据库连接池,以及mysql驱动。
然后我们需要在项目中添加spring的配置文件applicationContext.xml,其内容如下:
<?xml version="1.0" encoding="UTF-8"?><!-- Copyright 2010 The myBatis Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.--><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 定义配置项 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:*jdbc.properties</value> </list> </property> </bean> <!-- 数据源配置,使用应用内的DBCP数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxIdle" value="${jdbc.maxIdle}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="defaultAutoCommit" value="false" /> <property name="validationQuery" value="select 1" /> <property name="testOnBorrow" value="true" /> </bean> <!-- transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- enable component scanning (beware that this does not enable mapper scanning!) <context:component-scan base-package="org.mybatis.jpetstore.service" />--> <!-- enable autowire --> <context:annotation-config /> <!-- enable transaction demarcation with annotations --> <tx:annotation-driven /> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="cn.outofmemory.hello.mybatis.console.pojo" /> </bean> <!-- scan for mappers and let them be autowired --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.outofmemory.hello.mybatis.console.persistence" /> </bean></beans>
各个配置节的说明在文件中都做了注释,和mybatis最为相关的是最后一个bean org.mybatis.spring.mapper.MapperScannerConfigurer
这个bean中定义了要扫描接口的jar表,mybatis会从这里定义的basePackage中来找到所有用户定义的接口文件,并根据接口文件来生成动态代理类。在bean sqlSessionFactory中我们定义了pojo类所在的jar包。
另外上述配置文件中的dataSource需要配置连接属性,其连接的配置文件我们定义为jdbc.properties放在src/main/resources的目录下,其内容如下:
jdbc.driverClassName=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://127.0.0.1/test?zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8jdbc.username=rootjdbc.password=rootjdbc.maxActive=20 jdbc.maxIdle=10jdbc.maxWait=4000
下面我们看下数据库操作的接口TodoMapper的定义:
package cn.outofmemory.hello.mybatis.console.persistence;import java.util.List;import cn.outofmemory.hello.mybatis.console.pojo.Todo;/** * TodoMapper * * 定义todo的持久层方法 * * @author cn.outofmemory * */public interface TodoMapper { void insert(Todo todo); List<Todo> getTodoList(); Todo getTodo(int id); int update(Todo todo); int delete(int id);}
在这个接口中我们定义可对Todo进行添加,修改,删除,查询的方法。
定义了接口文件之后就需要在资源文件中定义对应的sql定义xml文件,其内容如下所示:
<?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="cn.outofmemory.hello.mybatis.console.persistence.TodoMapper"> <cache/> <insert id="insert" parameterType="Todo" useGeneratedKeys="true" keyProperty="id"> insert into todo (title,createTime) values (#{title},#{createTime}) </insert> <select id="getTodo" parameterType="int" useCache="true" resultType="Todo"> select * from todo where id = #{id} </select> <select id="getTodoList" resultType="Todo" useCache="false"> select * from todo </select> <update id="update" parameterType="Todo"> update todo set title = #{title} where id=#{id} </update> <delete id="delete" parameterType="int"> delete from todo where id = #{id} </delete></mapper>
这里xml中定义的sql和接口中定义的方法一一对应,参数类型和返回值必须是一致的,注意在mybatis中定义的参数个数仅能有一个,一般情况下也就够用了。
下面我们看下如何使用上述类类完成对Todo表的操作,如下是App.java代码:
package cn.outofmemory.hello.mybatis.console;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import cn.outofmemory.hello.mybatis.console.persistence.TodoMapper;import cn.outofmemory.hello.mybatis.console.pojo.Todo;import java.util.List;import java.util.Date;/** * Hello world! * */public class App { public static void main( String[] args ) { ApplicationContext appContext = new ClassPathXmlApplicationContext("/applicationContext.xml"); TodoMapper mapper = appContext.getBean(TodoMapper.class); Todo todo = new Todo(); todo.setTitle("这是今天的todo"); todo.setCreateTime(new Date()); mapper.insert(todo); System.out.println("todo's new id is " + todo.getId()); Todo todo1 = mapper.getTodo(1); System.out.println("todo's title is " + todo1.getTitle()); List<Todo> todoes = mapper.getTodoList(); System.out.println("todoes count equals " + todoes.size()); todo1.setTitle("modified title"); mapper.update(todo1); mapper.delete(todo.getId()); }}
上述main方法首先初始化了ApplicationContext,然后就可以从这个配置中载入接口的实现,然后就可以使用接口进行数据库的操作了。
上述方法都是很基础的方法,如下是示例项目的所有代码:
下载mybatis示例项目
用户点评