mybatis自帶常用操作資料庫方法詳解以及如何搭建簡單的mybatis環境
首先我們介紹一下mybatis中一些自帶常用的方法,後面我們介紹如何搭建mybatis環境
① selectByPrimaryKey()
User user = userDAO.selectByPrimaryKey(100); 相當於select * from user where id = 100
② selectByExample() 和 selectByExampleWithBLOGs()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
criteria.andUsernameIsNull();
example.setOrderByClause("username asc,email desc");
List<?>list = userDAO.selectByExample(example);
相當於:select * from user where username = 'joe' and username is null order by username asc,email desc
注:在iBator 生成的檔案UserExample.java中包含一個static 的內部類 Criteria ,在Criteria中有很多方法,主要是定義SQL 語句where後的查詢條件。
③ insert()
User user = new User();
user.setId(101);
user.setUsername("test");
user.setPassword("123")
user.setEmail("");
userDAO.insert(user);
相當於:insert into user(ID,username,password,email) values(101,'test','123','');
④ updateByPrimaryKey() 和 updateByPrimaryKeySelective()
User user =new User();
user.setId(101);
user.setUsername("joe");
user.setPassword("joe");
user.setEmail("");
userDAO.updateByPrimaryKey(user);
相當於:update user set username='joe',password='joe',email='' where id=101
User user = new User();
user.setId(101);
user.setPassword("joe");
userDAO.updateByPrimaryKeySelective(user);
相當於:update user set password='joe' where id=101
⑤updateByExample() 和 updateByExampleSelective()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
User user = new User();
user.setPassword("123");
userDAO.updateByPrimaryKeySelective(user,example);
相當於:update user set password='123' where username='joe'
⑥deleteByPrimaryKey()
userDAO.deleteByPrimaryKey(101); 相當於:delete from user where id=101
⑦ deleteByExample()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
userDAO.deleteByExample(example);
相當於:delete from user where username='joe'
⑧ countByExample()
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
criteria.andUsernameEqualTo("joe");
int count = userDAO.countByExample(example);
相當於:select count(*) from user where username='joe'
.......................................................我是分割線,下面就是如何搭建專案................................................................
1,第一步你應該建立好自己的資料庫
CREATE DATABASE /*!32312 IF NOT EXISTS*/`myproject` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */;
USE `myproject`;
CREATE TABLE `role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL,
`detail` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
CREATE TABLE `sysuser` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '使用者名稱',
`password` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '密碼',
`name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '姓名',
`detail` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '備註',
`roleId` bigint(20) DEFAULT NULL COMMENT '角色ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
2,在myeclipse中建立好專案,MySSIProject。
3,匯入所需基礎jar包
log4j-1.2.16.jar #mybatis的日誌是基於log4j的
mybatis-3.0.6.jar #mybatis核心包,肯定少不了,我是用的版本是3
mybatis-generator-core-1.3.1.jar #mybatis自動生成檔案的包,如果需要自動生成檔案則匯入
mysql-connector-java-5.1.6-bin.jar #mysql資料庫連線工具(本人使用的是mysql資料庫)
4,在工程建立包結構,後面自動生成程式碼需要指定生成在什麼位置
5,在MySSIProject專案根目錄下新建generatorConfig.xml檔案,用來實現自動生成mybatis配置檔案,內容如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 資料庫驅動 指定mysql連結jar包位置 -->
<classPathEntry location="D:/workspace/MySSIProject/WebRoot/WEB-INF/lib/mysql-connector-java-5.1.6-bin.jar" />
<context id="MyBatis3" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true" />
</commentGenerator>
<!-- 資料庫配置 地址 使用者名稱 密碼 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/myproject"
userId="root"
password="root">
</jdbcConnection>
<!-- model配置 指定那個包存放資料庫實體類 targetProject為專案src檔案在硬碟實際路徑 -->
<javaModelGenerator targetPackage="com.itcast.database.model" targetProject="D:/workspace/MySSIProject/src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- dao配置 指定那個包存放資料庫操作檔案-->
<sqlMapGenerator targetPackage="com.itcast.database.dao" targetProject="D:/workspace/MySSIProject/src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.itcast.database.dao" targetProject="D:/workspace/MySSIProject/src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定需要自動生成檔案的表 tableName為表名 domainObjectName為系統生成後名字 -->
<table tableName="sysuser" domainObjectName="sysuser"></table>
<table tableName="role" domainObjectName="role"></table>
</context>
</generatorConfiguration>
說明:以上location,targetProject路徑均為所需檔案所在硬碟具體實際位置,
6.開啟cmd視窗,進入你專案的根目錄 比如我就是進入:D:\workspace\MySSIProject> 因為的的專案在這個位置。(當然你也可以不這麼做,我的目的是找到generatorConfig.xml配置檔案,畢竟他就在這裡,你在別的位置只要後面指定generatorConfig.xml時把路徑寫對就好),然後輸入:java -jar WebRoot/WEB-INF/lib/mybatis-generator-core-1.3.1.jar -configfile generatorConfig.xml -overwrite (這是一行命令),回車執行,見到MyBatis Generator finshed successfully.你就可以去專案看你的傑作了。好運