Mybatis博客推荐 http://limingnihao.iteye.com/blog/781671
前言:之前一直使用hibernate在作为数据层的持久化框架,也用过mybatis,但是觉得要写的sql太多很麻烦, 所以使用的不多 。 现在数据层使用的是mybatis,前端mvc框架用的是他们自己研发的webx3框架,所以决定研究一下这两个框架。 首先研究mybatis
,学习教程是官方的《MyBatis-3-User-Guide-Simplified-Chinese》,去mybatis官网就能下载。 可能会分为十章左右,项目文件在文章最后能够下载
有时间再继续写一套webx3的学习笔记。
本次学习以代码实例为主,不会研究的太深入。 写这个笔记主要是为了让自己尽快熟悉mybatis并且方便以后复习 。 顺便提供给想简单学习mybatis的同学参考。
新建项目(我使用的是maven项目)mybatis-study-01
一、加入mybatis与mysql-connector依赖包到pom文件
<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>mybatis</groupId> <artifactId>mybatis-study-01</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>mybatis-01</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> </dependencies> </project>
新建一张user表用于测试。建表sql如下:
CREATE TABLE `user` ( `id` int(11) NOT NULL auto_increment, `password` varchar(255) default NULL, `user_name` varchar(50) default NULL, `user_age` int(11) default NULL, `user_address` varchar(200) default NULL, PRIMARY KEY (`id`), UNIQUE KEY `userName` (`user_name`) ) EN
插入一条数据
INSERT INTO `user` VALUES ('1', '123131', 'summer', '100', 'shanghai,pudong');
三、在项目中编写pojo对象。
package com.zf.mybatis.pojo; public class User { private int id; private String password ; private String userName; private String userAge; private String userAddress; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserAge() { return userAge; } public void setUserAge(String userAge) { this.userAge = userAge; } public String getUserAddress() { return userAddress; } public void setUserAddress(String userAddress) { this.userAddress = userAddress; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
四、编写pojo对应的映射文件User.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="com.zf.mybatis.pojo.UserMapper"> <!-- 使用sql标签可以将公共的sql提取出来复用 --> <sql id="queryFields"> id , password , user_name as userName , user_age as userAge , user_address as userAddress </sql> <select id="selectByID" parameterType="int" resultType="User"> select <include refid="queryFields"/> from `user` where id = #{id} </select> <insert id="add" parameterType="User" useGeneratedKeys="true" keyProperty="id" > insert into `user` (password , user_name , user_age , user_address) values(#{password} , #{userName} , #{userAge} , #{userAddress} ) </insert> <update id="update" parameterType="User" > update `user` set password = #{password} , user_name = #{userName}, user_age = #{userAge}, user_address = #{userAddress} where id = #{id} </update> <delete id="deleteById" parameterType="int"> delete from `user` where id = #{id} </delete> </mapper>
另外,mybatis会将从数据库查询出来的记录根据列名与pojo中的字段进行匹配, 所以上面的user_name,user_age ,user_address这几个字段都取了别名,跟pojo中的字段相对应。 如果不起别名, 查询出来的对象,这几个字段是没有值的。
五、编写mybatis的配置文件mybatis-config.xml
<?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> <!-- 配置别名 --> <typeAliases> <typeAlias alias="User" type="com.zf.mybatis.pojo.User"/> </typeAliases> <!-- 数据库配置信息 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis-test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="conf/User.xml"/> </mappers> </configuration>在该配置文件中配置了数据库的链接方式,以及注册所有的映射文件,还可以设置mybatis的一些参数。
现在就可以编写测试类了。来测试一下。
package com.zf.mybatis; import java.io.IOException; import java.io.Reader; 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 com.zf.mybatis.pojo.User; public class TestMyBatis { private SqlSessionFactory sqlSessionFactory; private Reader reader; @Before public void init(){ try { reader = Resources.getResourceAsReader("mybatis-config.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (IOException e) { e.printStackTrace(); } } @Test public void testQueryUser(){ SqlSession session = sqlSessionFactory.openSession(); try { User user = (User) session.selectOne("com.zf.mybatis.pojo.UserMapper.selectByID" ,1); System.out.println(user.getUserAddress()); System.out.println(user.getUserName()); } finally { session.close(); } } @Test public void testInsertUser(){ SqlSession session = sqlSessionFactory.openSession(); try { User user = new User() ; user.setUserName("abcde"); user.setUserAge(15) ; user.setUserAddress("hangzhou/zhejiang"); user.setPassword("123456"); //返回值是记录条数 int resultCount = session.insert("com.zf.mybatis.pojo.UserMapper.add", user ); session.commit() ; System.out.printf("userID:%d,总记录条数:%d" , user.getId() , resultCount); //获取插入对象的id } finally { session.close(); } } @Test public void testUpdateUser(){ SqlSession session = sqlSessionFactory.openSession(); try { User user = new User() ; user.setId(5) ; user.setUserName("updateName"); user.setUserAge(101) ; user.setUserAddress("shenzhen/guangdong"); user.setPassword("000000"); //返回值是修改条数 int updateCount = session.update("com.zf.mybatis.pojo.UserMapper.update", user ); session.commit() ; System.out.printf("修改条数:%d" ,updateCount); } finally { session.close(); } } @Test public void testDelete(){ SqlSession session = sqlSessionFactory.openSession(); try { //返回值是删除条数 int deleteCount = session.update("com.zf.mybatis.pojo.UserMapper.deleteById", 4 ); session.commit() ; System.out.printf("删除条数:%d" ,deleteCount ); } finally { session.close(); } } }
运行testQueryUser结果如下:
shanghai,pudong summer到此,一个mybatis的helloworld类型的小程序就出来了。
下载项目文件 mybatis-study-01.zip