之前一直有用Hibernate进行开发。近期公司在使用Mybatis。依据网上的演示样例,做了一个简单的Demo,以便日后复习
使用XMl方式映射sql语句
整体结构例如以下图
首先是创建一个project,然后导入两个jar包,然后编写mybatis的jdbc配置文件Configuration.xml
Configuration.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> <!-- 为sql映射文件里的类型指定别名,假设不加alias,则整个包下的别名都是类名 --> <typeAliases> <typeAlias type="com.demo.bean.User" alias="User"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="oracle.jdbc.driver.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" /> <property name="username" value="scott" /> <property name="password" value="scott" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/demo/bean/User.xml" /> </mappers> </configuration>
User类。文章中省略getter和setter方法
package com.demo.bean; import java.util.Date; public class User { private String id; private String name; private String password; private Date birthday; private String address; }
然后是创建sql映射文件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.demo.bean.User"> <!-- 查询全部用户, resultType代表返回类型(一般写全限定类名。也能够在mybatis配置文件里指定别名),parameterType代表參数类型 --> <select id="selectAllUsers" resultType="User"> select * from valid_user </select> <!-- 依据id查询用户 --> <select id="findUserById" parameterType="int" resultType="User"> select * from valid_user where id=#{id} </select> <!-- 依据id更新用户 --> <update id="updateUserById" parameterType="User"> update valid_user set name=#{name},address=#{address} where id=#{id} </update> <!-- 加入新用户 --> <insert id="addUser" parameterType="User"> insert into valid_user(id,name,password,address) values(seq_valid_user.nextval,#{name},#{password},#{address}) </insert> <!-- 依据id删除用户 --> <delete id="deleteUserById" parameterType="int"> delete from valid_user where id=#{id} </delete> </mapper>然后就是编辑測试类
package com.demo.Test; import java.io.Reader; import java.util.List; 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 com.demo.bean.User; public class TestConnection { private static SqlSessionFactory sqlSessionFactory; private static Reader reader; static { try { reader = Resources.getResourceAsReader("Configuration.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } catch (Exception e) { e.printStackTrace(); } } /** * 查询全部User对象 * @param id */ public static void selectAllUsers() { SqlSession session = sqlSessionFactory.openSession(); try { List<User> listUsers = session.selectList("com.demo.bean.User.selectAllUsers"); for (User user:listUsers) { System.out.println("ID:" + user.getId() + ",姓名:" + user.getName() + ",password:" + user.getPassword() + ",住址:" + user.getAddress()); } } finally { session.close(); } } /** * 依据id查询User对象 * @param id */ public static void findUserById(String id) { SqlSession session = sqlSessionFactory.openSession(); try { User user = (User) session.selectOne("com.demo.bean.User.findUserById", id); System.out.println("ID:" + user.getId() + ",姓名:" + user.getName() + ",password:" + user.getPassword() + ",住址:" + user.getAddress()); } finally { session.close(); } } /** * 依据id更新User对象 * @param id */ public static void updateUserById(String id,User user) { SqlSession session = sqlSessionFactory.openSession(); try { session.update("com.demo.bean.User.updateUserById",user); session.commit(); } finally { session.close(); } } /** * 加入一条User对象 */ public static void addUser(User user) { SqlSession session = sqlSessionFactory.openSession(); try { session.insert("com.demo.bean.User.addUser",user); session.commit(); } finally { session.close(); } } /** * 删除一条User对象 */ public static void deleteUserById(String id) { SqlSession session = sqlSessionFactory.openSession(); try { session.delete("com.demo.bean.User.deleteUserById",id); session.commit(); } finally { session.close(); } } public static void main(String[] args) { selectAllUsers(); // findUserById("1"); // 依据id查询User对象 // User user=new User(); // user.setId("2"); // user.setName("Zams"); // user.setAddress("河南、郑州"); // updateUserById("2",user); // 依据id更新User对象 // User add_user=new User(); // add_user.setName("古力娜扎"); // add_user.setPassword("3412312"); // add_user.setAddress("河南、郑州、开封"); // addUser(add_user); // 依据id更新User对象 // deleteUserById("4"); } }
执行效果例如以下;
ID:1,姓名:X-rapido,password:rapido,住址:北京朝阳、海淀 ID:2,姓名:Zams,password:gril,住址:河南、郑州 ID:3,姓名:盖尔加朵,password:3412312,住址:河南、郑州 ID:5,姓名:古力娜扎,password:3412312,住址:河南、郑州、开封
其它内容:
- SqlSession session = sqlSessionFactory.openSession(); 能够设置事务的自己主动提交。
- 配置文件里的jdbc联接能够写在properties文件里。
- Mybatis的sql映射能够使用xml的形式,如上面内容,也能够使用java注解方式。
- 映射文件里能够配置多表连接方式。參考其它文档,未做演示样例
- 另外mybatis能够配置动态sql语句形式、调用存储过程、为sql语句字段指定别名(一般数据库字段与java类字段不同一时候须要指定)
- Mybatis的sql打印并不像Hibernate那样有设置sql打印的參数。它须要与log4j.jar包进行配合才干打印
使用Java注解方式映射sql语句
使用注解方式的演示样例结构例如以下
整体结构内容不变,主要改动java注解配置类(Service类)、配置文件、測试类3个地方就可以
UserMapper类
package com.demo.bean; import java.util.List; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; /** * 使用注解映射,不须要写实现类,但要在Mybatis配置文件里将此类进行注冊 */ public interface UserMapper { @Select("select * from valid_user") List<User> selectAllUsers(); @Select("select * from valid_user where id=#{id}") User findUserById(String id); @Update("update valid_user set name=#{name},address=#{address} where id=#{id}") int updateUserById(User user); @Insert("insert into valid_user(id,name,password,address) values(seq_valid_user.nextval,#{name},#{password},#{address})") int addUser(User user); @Delete("delete from valid_user where id=#{id}") int deleteUserById(String id); }Mybatis配置文件里 configuration.xml改动 mapper内容
<mappers> <mapper class="com.demo.bean.UserMapper" /> </mappers>将測试类中的如查询全部代码的com.demo.bean.User.selectAllUsers改动为com.demo.bean.UserMapper.selectAllUsers就可以。
測试效果同xml的配置效果一样。
在实际应用中。有时候须要对Mybatis进行多參数传值,这时候能够使用Map对象进行查询
比方在登录时。传入账户名和password,在xml在将 parameterType设置为map參数类型, parameterType="map"
Map<String, String> map = new HashMap<String, String>(); map.put("name", userName); map.put("password", password); return sqlSession.selectOne("com.demo.bean.User.loginUser", map);
设置log4j,打印SQL运行语句
log4j的配置文件能够是xml形式,也能够是.properties文件形式
log4j.properties(方式一)
log4j.rootLogger=DEBUG, Console #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=DEBUGlog4j.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) " /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="debug" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration>