一. 一个简短的引论:
Mybatis本是apache的一个开源项目ibatis, 2010年这个项目由apache software foundation迁移到了google code, 而且改名为Mybatis.
Mybatis是一个基于Java的持久层框架.
二. 增删改查:
1. 代码结构图:
2. User实体类:
/** * User实体类 */ public class User { private String id; private String uname; // 注意: 该字段名称与数据库字段不一致 private String address; @Override public String toString() { return "{id: " + id + ", uname: " + uname + ", address: " + address + "}"; } }
// 省略getter和setter方法
3. 实体映射文件: 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.zdp.domain.User"> <!-- 数据库字段与实体字段相应 --> <resultMap type="User" id="userBean"> <id column="id" property="id"/> <result column="username" property="uname"/> <result column="address" property="address"/> </resultMap> <!-- 查: 查询全部User --> <select id="selectAllUsers" resultMap="userBean"> select id, username, address from user </select> <!-- 查: 依据id查询User, 返回值为userBean --> <!-- id:当前sql语句的唯一标识, parameterType:參数类型, resultType:返回值类型 --> <select id="selectUserById" parameterType="string" resultMap="userBean"> select * from user where id = #{userid} </select> <!-- 查: 依据id查询User, 返回值为HashMap --> <select id="selectUserByIdForMap" parameterType="string" resultType="hashmap"> select id, username, address from user where id = #{userid} </select> <!-- 增: 插入User, 參数为userBean(调用getter方法获取參数值) --> <insert id="insertUser" parameterType="User"> insert into user(id, username, address) values (#{id}, #{uname}, #{address}); </insert> <!-- 增: 插入User, 參数为hashmap(调用userMap.get(key)获取參数) --> <insert id="insertUserForMap" parameterType="hashmap"> insert into user(id, username, address) values (#{id}, #{uname}, #{address}); </insert> <!-- 删: 依据id删除User, 參数为userId --> <delete id="deleteUserById" parameterType="string"> delete from user where id = #{userid} </delete> <!-- 改: 依据id更新User, 參数为userBean(调用getter方法获取參数值) --> <update id="updateUserById" parameterType="User"> update user set username = #{uname}, address = #{address} where id = #{id} </update> <!-- 改: 依据id更新User, 參数为map(调用userMap.get(key)获取參数) --> <update id="updateUserByIdForMap" parameterType="hashmap"> update user set username = #{uname}, address = #{address} where id = #{id} </update> <!-- 查: 动态sql: 使用 "where 1=1" --> <select id="selectUserByCondition1" parameterType="User" resultMap="userBean"> select id, username, address from user where 1=1 <if test="id != null"> and id = #{id} </if> <!-- uname指的是实体的属性 --> <if test="uname != null"> and username = #{uname} </if> <if test="address != null"> and address = #{address} </if> </select> <!-- 查: 动态sql: 使用where标签 --> <select id="selectUserByCondition2" parameterType="User" resultMap="userBean"> select id, username, address from user <where> <if test="id != null"> id = #{id} </if> <!-- uname指的是实体的属性 --> <if test="uname != null"> and username = #{uname} </if> <if test="address != null"> and address = #{address} </if> </where> </select> </mapper>
4. 全局配置文件:sqlMapConfig.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 type="com.zdp.domain.User" alias="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://localhost/test" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <!-- 映射文件的位置 --> <mapper resource="com/zdp/domain/User.xml" /> </mappers> </configuration>
typeAliases: 为java类型指定别名, 能够再xml文件里用别名替代java类的全限定名.
5. sql文件:
CREATE DATABASE test; USE test; CREATE TABLE USER( id VARCHAR(36) PRIMARY KEY, username VARCHAR(64), address VARCHAR(128) ) INSERT INTO USER (id, username, address) VALUES("001", "zhangsan", "Wuhan"); INSERT INTO USER (id, username, address) VALUES("002", "lisi", "Shanghai");
6. log4j
log4j.rootLogger=DEBUG, Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
7. 測试文件:
/** * 測试mybatis - user增删改查 */ public class UserTest { private SqlSessionFactory ssf; @Before public void initSF() throws Exception { String resource = "sqlMapConfig.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); ssf = new SqlSessionFactoryBuilder().build(inputStream); } // 查询全部User @Test public void testSelectAllUsers() throws Exception { SqlSession session = ssf.openSession(); List<User> users = session.selectList("com.zdp.domain.User.selectAllUsers"); for (User user : users) { System.out.println(user); } } // 依据id查询User, 返回值为userBean @Test public void testSelectUserById() throws Exception { SqlSession session = ssf.openSession(); User user = session.selectOne("com.zdp.domain.User.selectUserById", "001"); System.out.println(user); } // 依据id查询User, 返回值为HashMap @Test public void testSelectUserByIdForMap() throws Exception { SqlSession session = ssf.openSession(); Map<String, Object> userMap = session.selectOne("com.zdp.domain.User.selectUserByIdForMap", "001"); System.out.println(userMap); } // 插入User, 參数为userBean @Test public void testInsertUser() throws Exception { SqlSession session = ssf.openSession(); // 构建实体 User user = new User(); user.setId("003"); user.setUname("wangwu"); user.setAddress("beijing"); int i = session.insert("com.zdp.domain.User.insertUser", user); // 提交事务 session.commit(); } // 插入User, 參数为hashmap @Test public void testInsertUserForMap() throws Exception { SqlSession session = ssf.openSession(); Map<String, Object> userMap = new HashMap<String, Object>(); userMap.put("id", "004"); userMap.put("uname", "zhaoliu"); userMap.put("address", "tianjin"); int i = session.insert("com.zdp.domain.User.insertUserForMap", userMap); session.commit(); } // 依据id删除User, 參数为userId @Test public void testDeleteUserById() throws Exception { SqlSession session = ssf.openSession(); int i = session.delete("com.zdp.domain.User.deleteUserById", "004"); session.commit(); } // 依据id更新User, 參数为userBean @Test public void testUpdateUserById() throws Exception { SqlSession session = ssf.openSession(); User user = new User(); user.setId("001"); user.setUname("zhangsanf"); user.setAddress("wuhan"); int i = session.update("com.zdp.domain.User.updateUserById", user); session.commit(); } // 依据id更新User, 參数为hashMap @Test public void testUpdateUserByIdForMap() throws Exception { SqlSession session = ssf.openSession(); Map<String, Object> userMap = new HashMap<String, Object>(); userMap.put("id", "001"); userMap.put("uname","zhangsan"); userMap.put("address", "beijing"); int i = session.update("com.zdp.domain.User.updateUserByIdForMap", userMap); session.commit(); } // 动态条件查询: @Test public void testSelectUserByCondition() throws Exception { SqlSession session = ssf.openSession(); User user = new User(); user.setUname("lisi"); List<User> users = session.selectList("com.zdp.domain.User.selectUserByCondition1", user); // List<User> users = session.selectList("com.zdp.domain.User.selectUserByCondition2", user); for (User u : users) { System.out.println(u); } } }
SqlSessionFactory是一个创建SqlSession的工厂类, 通过SqlSession实例, 开发人员可以直接进行业务逻辑的操作, 二不须要反复编写JDBC相关的模板代码.
版权声明:本文博主原创文章,博客,未经同意不得转载。
时间: 2024-10-29 19:10:50