mybatis 是apache下的一個面向sql編程的半自動化的ORM持久層的框架。特點:面向sql編程,達到高性能的使用目的。 下麵是簡單使用 現導入jar包,只有mybatis和資料庫驅動包(這裡用的是mysql的驅動包)是必須的,其餘是日誌需要的包 db.properties配置連接池的配置文 ...
mybatis 是apache下的一個面向sql編程的半自動化的ORM持久層的框架。特點:面向sql編程,達到高性能的使用目的。
下麵是簡單使用
現導入jar包,只有mybatis和資料庫驅動包(這裡用的是mysql的驅動包)是必須的,其餘是日誌需要的包
db.properties配置連接池的配置文件
1 jdbc.driverClassName=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/mybatis 3 jdbc.username=root 4 jdbc.password=12
創建一個mybatis資料庫,執行下麵的生sql語句插入數據
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) NOT NULL COMMENT '用戶名稱', `birthday` date DEFAULT NULL COMMENT '生日', `sex` char(1) DEFAULT NULL COMMENT '性別', `address` varchar(256) DEFAULT NULL COMMENT '地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', '王五', null, '2', null); INSERT INTO `user` VALUES ('10', '張三', '2014-07-10', '1', '北京市'); INSERT INTO `user` VALUES ('16', '張小明', null, '1', '河南鄭州'); INSERT INTO `user` VALUES ('22', '陳小明', null, '1', '河南鄭州'); INSERT INTO `user` VALUES ('24', '張三豐', null, '1', '河南鄭州'); INSERT INTO `user` VALUES ('25', '陳小明', null, '1', '河南鄭州'); INSERT INTO `user` VALUES ('26', '王五', null, null, null);
log4j.properties 日誌的配置文件
1 ### direct log messages to stdout ### 2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 3 log4j.appender.stdout.Target=System.err 4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 5 log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n 6 7 ### direct messages to file mylog.log ### 8 log4j.appender.file=org.apache.log4j.FileAppender 9 log4j.appender.file.File=d:/mylog.log 10 log4j.appender.file.layout=org.apache.log4j.PatternLayout 11 log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n 12 13 ### set log levels - for more verbose logging change 'info' to 'debug' ### 14 15 log4j.rootLogger=info, stdout
SqlMapConfig.xml 是mybatis全局的配置文件
<?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> <properties resource="db.properties"> </properties> <typeAliases> <!-- 單個別名定義 ,後面就可用直接寫user,不用寫全路徑名--> <!-- <typeAlias type="com.baoyuan.domain.User" alias="user"/> --> <!-- 批量別名定義,掃描整個包下的類,別名為類名(大小寫不敏感) --> <package name="com.baoyuan.domain"/> </typeAliases> <!--名稱隨意 --> <environments default="development"> <!--id必須和上面的一致 --> <environment id="development"> <!--固定格式JDBC --> <transactionManager type="JDBC"></transactionManager> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <!-- 使用mapper介面類路徑 註意:此種方法要求mapper介面名稱和mapper映射文件名稱相同,且放在同一個目錄中--> <!-- <mapper class="com.baoyuan.mapper.dao.UserMapper"/> --> <!-- 註意:此種方法要求mapper介面名稱和mapper映射文件名稱相同,且放在同一個目錄中。 --> <package name="com.baoyuan.mapper.dao"/> </mappers> </configuration>
創建一個pojo類User類
package com.baoyuan.domain; import java.util.Date; public class User { private Integer id; private String username;// 用戶姓名 private String sex;// 性別 private Date birthday;// 生日 private String address;// 地址 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "User [id=" + id + ", username=" + username + ", sex=" + sex + ", birthday=" + birthday + ", address=" + address + "]"; } }
在src目錄下建立一個com.baoyuan.mapper.dao的包
在com.baoyuan.mapper.dao創建一個UserMapper.xml的映射文件
Mapper介面開發需要遵循以下規範:
1、 Mapper.xml文件中的namespace與mapper介面的類路徑相同。
2、 Mapper介面方法名和Mapper.xml中定義的每個statement的id相同
3、 Mapper介面方法的輸入參數類型和mapper.xml中定義的每個sql 的parameterType的類型相同
4、 Mapper介面方法的輸出參數類型和mapper.xml中定義的每個sql的resultType的類型相同
<?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.baoyuan.mapper.dao.UserMapper">
<!-- Id表示statement的id唯一標識符,resultType表示結果集的類型,parameterType表示形式參數類型 ,如果SqlMapConfig.xml中配置了別名,就可以直接謝別名user,不用再寫全路徑com.baoyuan.domain.User --> <select id="findUserById" resultType="com.baoyuan.domain.User" parameterType="int" >
<!--#{}大括弧類隨意寫只是表示一個占位符,相當於statment中的"?" --> select * from user where id =#{id} </select>
<!--這裡返回的類型雖然是list,resultType表示list泛型的類型 --> <select id="findUserByUsername" resultType="com.baoyuan.domain.User" parameterType="java.lang.String" >
<!--這裡必須寫value,${value}表示拼接字元串,如果用其他會報錯,用#{}只是表示占位符,可以在調用時傳"%條件%的參數" --> select * from user where username like '%${value}%' </select> <insert id="saveUser" parameterType="com.baoyuan.domain.User" >
<!--配置在插入一條數據後返回主鍵,會自動保存到pojo對象的主鍵屬性中 -->
<selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
select LAST_INSERT_ID()
<!--必須是主鍵自增長 是mysql的函數,返回auto_increment自增列新記錄id值 -->
</selectKey>
<!-- <selectKey resultType="java.lang.String" order="BEFORE" keyProperty="id">
select uuid()
需要增加通過select uuid()得到uuid值(前提是用戶表中的id必須是字元串類型)
</selectKey> -->
<!--這裡由於 parameterType形式參數的類型是user,所以這裡#{}大括弧中不能隨便寫,寫的是user的屬性 --> insert INTO user(username,birthday,sex,address) VALUES(#{username},#{birthday},#{sex},#{address}) </insert> <delete id="deleteUserById" parameterType="int"> delete from user where id =#{id} </delete> <update id="updateUserById" parameterType="com.baoyuan.domain.User"> update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id} </update> </mapper>
創建UserMapper的介面
package com.baoyuan.mapper.dao; import java.util.List; import com.baoyuan.domain.User; //類名必須和 public interface UserMapper { public User findUserById(Integer id); public List<User> findUserByUsername(String username); public void saveUser(User user); public void deleteUserById(Integer id); public void updateUserById(User user); }
測試代碼
package com.baoyuan.test; import java.io.IOException; import java.io.InputStream; import java.util.Date; 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 org.junit.Before; import org.junit.Test; import com.baoyuan.domain.User; import com.baoyuan.mapper.dao.UserMapper; public class TestUserMapper { private SqlSessionFactory sqlSessionFactory ;
//表示運行測試代碼前執行,給sqlSessionFactory賦值 @Before public void InitialContext() throws IOException{ SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); InputStream inputStream=Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory = builder.build(inputStream); this.sqlSessionFactory=sqlSessionFactory; }
//通過id查詢用戶 @Test public void findUserById(){ //獲取sqlsession SqlSession sqlSession=null; try { sqlSession = sqlSessionFactory.openSession(); //獲取mapper介面代理對象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = userMapper.findUserById(1); System.out.println(user); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(sqlSession!=null){ sqlSession.close(); } } }
//通過用戶名模糊查詢用戶 @Test public void findUserByUsername(){ //獲取sqlsession SqlSession sqlSession=null; try { sqlSession = sqlSessionFactory.openSession(); //獲取mapper介面代理對象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> list = userMapper.findUserByUsername("張"); System.out.println(list); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ if(sqlSession!=null){ sqlSession.close(); } } }
//保存用戶 @Test public void saveUser(){ //獲取sqlsession SqlSession sqlSession=null; try { sqlSession = sqlSessionFactory.openSession(); //獲取mapper介面代理對象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user=new User(); user.setUsername("李四"); user.setBirthday(new Date()); user.setSex("1"); user.setAddress("深圳");
System.out.println(user.getId()); userMapper.saveUser(user); sqlSession.commit();
System.out.println(user.getId()); } catch (Exception e) { e.printStackTrace(); }finally{ if(sqlSession!=null){ sqlSession.close(); } } }
//更新用戶 @Test public void updateUserById(){ //獲取sqlsession SqlSession sqlSession=null; try { sqlSession = sqlSessionFactory.openSession(); //獲取mapper介面代理對象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user=new User(); user.setId(30); user.setUsername("李四"); user.setBirthday(new Date()); user.setSex("1"); user.setAddress("深圳"); userMapper.updateUserById(user);; sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); }finally{ if(sqlSession!=null){ sqlSession.close(); } } }
//刪除用戶 @Test public void deleteUserById(){ //獲取sqlsession SqlSession sqlSession=null; try { sqlSession = sqlSessionFactory.openSession(); //獲取mapper介面代理對象 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); userMapper.deleteUserById(30);; sqlSession.commit(); } catch (Exception e) { e.printStackTrace(); }finally{ if(sqlSession!=null){ sqlSession.close(); } } } }