用mybatis原因很簡單,易用,性能。是介于jdbc和hibernate之間的一個完美方案。
很簡單:
1:配置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 > com.test.database </ groupId > < artifactId > dao-core </ artifactId > < version > 0.0.1-SNAPSHOT </ version > < dependencies > < dependency > < groupId > org.mybatis </ groupId > < artifactId > mybatis </ artifactId > < version > 3.1.1 </ version > </ dependency > < dependency > < groupId > mysql </ groupId > < artifactId > mysql-connector-java </ artifactId > < version > 5.1.30 </ version > </ dependency > < dependency > < groupId > junit </ groupId > < artifactId > junit </ artifactId > < version > 4.7 </ version > < type > jar </ type > < scope > test </ scope > </ dependency > </ dependencies > < build > < plugins > <!-- mybits dao層 自動生成代碼 插件 --> < plugin > < groupId > org.mybatis.generator </ groupId > < artifactId > mybatis-generator-maven-plugin </ artifactId > < version > 1.3.2 </ version > < configuration > < verbose > true </ verbose > < overwrite > true </ overwrite > </ configuration > </ plugin > </ plugins > </ build > </ project >
2:?src/main/resources 下新建?generatorConfig.xml
<? 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 > <!-- classPathEntry:數據庫的JDBC驅動 --> < classPathEntry location ="D:\soft_源程序\DB\mysql\mysql-connector-java-5.1.19-bin.jar" /> < context id ="MysqlTables" targetRuntime ="MyBatis3" > <!-- 注意這里面的順序確定的,不能隨變更改 --> <!-- 自定義的分頁插件 <plugin type="com.deppon.foss.module.helloworld.shared.PaginationPlugin"/> --> <!-- 可選的(0 or 1) --> <!-- 注釋生成器 --> < commentGenerator > <!-- 是否去除自動生成的注釋 true:是 : false:否 --> < property name ="suppressAllComments" value ="true" /> </ commentGenerator > <!-- 必須的(1 required) --> <!-- 數據庫連接的信息:驅動類、連接地址、用戶名、密碼 --> < jdbcConnection driverClass ="com.mysql.jdbc.Driver" connectionURL ="jdbc:mysql://localhost:3306/data?useUnicode=true&characterEncoding=UTF-8" userId ="root" password ="123654" > </ jdbcConnection > <!-- 可選的(0 or 1) --> <!-- 類型轉換器或者加類型解析器 --> <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析為 Integer true,把JDBC DECIMAL 和 NUMERIC 類型解析為java.math.BigDecimal --> < javaTypeResolver > < property name ="forceBigDecimals" value ="false" /> </ javaTypeResolver > <!-- 必須的(1 required) --> <!-- java模型生成器 --> <!-- targetProject:自動生成代碼的位置 --> < javaModelGenerator targetPackage ="com.test.model" targetProject ="F:\Workspaces\workspace_eclipse\dao-core\src\main\java" > <!-- TODO enableSubPackages:是否讓schema作為包的后綴 --> < property name ="enableSubPackages" value ="true" /> <!-- 從數據庫返回的值被清理前后的空格 --> < property name ="trimStrings" value ="true" /> </ javaModelGenerator > <!-- 必須的(1 required) --> <!-- map xml 生成器 --> < sqlMapGenerator targetPackage ="com.test.persistence" targetProject ="F:\Workspaces\workspace_eclipse\dao-core\src\main\resources" > < property name ="enableSubPackages" value ="true" /> </ sqlMapGenerator > <!-- 可選的(0 or 1) --> <!-- mapper 或者就是dao接口生成器 --> < javaClientGenerator targetPackage ="com.test.dao" targetProject ="F:\Workspaces\workspace_eclipse\dao-core\src\main\java" type ="XMLMAPPER" > < property name ="enableSubPackages" value ="true" /> </ javaClientGenerator > <!-- 必須的(1...N) --> <!-- pojo 實體生成器 --> <!-- tableName:用于自動生成代碼的數據庫表;domainObjectName:對應于數據庫表的javaBean類名 --> <!-- schema即為數據庫名 可不寫 --> < table schema ="data" tableName ="tab_city" domainObjectName ="CityModel" enableInsert ="true" > <!-- 忽略字段 可選的(0 or 1) --> <!-- <ignoreColumn column="is_use" /> --> <!-- //無論字段是什么類型,生成的類屬性都是varchar。 可選的(0 or 1) 測試無效 --> <!-- <columnOverride column="city_code" jdbcType="VARCHAR" /> --> </ table > </ context > </ generatorConfiguration >
?
?
3: 點擊pom,run as maven bulid ?: ? mybatis-generator:generate ? ? 紅色字最好自己手敲或者copy.?
構建完后:
4:項目中使用的話,需要建立?mybatis-config.xml 在?src/main/resources 下
<? 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 > < 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:3306/data" /> < property name ="username" value ="root" /> < property name ="password" value ="123654" /> </ dataSource > </ environment > </ environments > < mappers > < mapper resource ="com/test/persistence/CityModelMapper.xml" /> </ mappers > <!-- <typeAliases> <typeAlias type="com.hoo.entity.Account" alias="account"/> </typeAliases> --> </ configuration >
5: 建立測試
5.1 java傳統測試
TestDao.java
package com.test.dao; 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 com.test.model.CityModel; public class TestDao { public static void main(String[] args) { SqlSession session = null ; String resource = "mybatis-config.xml" ; Reader reader = null ; try { reader = Resources.getResourceAsReader(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder() .build(reader); session = sessionFactory.openSession(); CityModelMapper cityModelMapper = session .getMapper(CityModelMapper. class ); // CityModel cityModel = new CityModel(); // cityModel.setId(7); // cityModel.setCityName("test7"); // cityModel.setCityCode(2); // cityModelMapper.insert(cityModel); // session.commit(); // System.out.println("插入一個city name" + cityModel.getCityName()); CityModel cityModel = cityModelMapper.selectByPrimaryKey(4 ); session.commit(); System.out.println(cityModel.getCityName()); cityModel.setCityName( "testchange" ); ; cityModelMapper.updateByPrimaryKey(cityModel); session.commit(); System.out.println( "update" ); } catch (IOException e) { e.printStackTrace(); } finally { if ( null != session) session.close(); } } }
5.2 單元測試:
CityModelMapperTest.java
package com.test.dao; import static org.junit.Assert.fail; import java.io.Reader; import java.util.List; import junit.framework.Assert; 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.After; import org.junit.Before; import org.junit.Test; import com.test.model.CityModel; import com.test.model.CityModelExample; public class CityModelMapperTest { SqlSession session = null ; CityModelMapper cityModelMapper = null ; @Before public void setUp() throws Exception { String resource = "mybatis-config.xml" ; Reader reader = null ; reader = Resources.getResourceAsReader(resource); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder() .build(reader); session = sessionFactory.openSession(); cityModelMapper = session.getMapper(CityModelMapper. class ); } @Test public void testCountByExample() { fail( "Not yet implemented" ); } @Test public void testDeleteByExample() { fail( "Not yet implemented" ); } @Test public void testDeleteByPrimaryKey() { int flag = cityModelMapper.deleteByPrimaryKey(10 ); session.commit(); System.out.println( "返回值:" + flag); System.out.println( "刪除一個city id " + 10 ); Assert.assertTrue(flag > 0 ); } @Test public void testInsert() { CityModel cityModel = new CityModel(); int i = 10 ; cityModel.setId(i); cityModel.setCityName( "test" + i); cityModel.setCityCode(i); cityModelMapper.insert(cityModel); session.commit(); System.out.println( "插入一個city name" + cityModel.getCityName()); } @Test public void testInsertSelective() { fail( "Not yet implemented" ); } @Test public void testSelectByExample() { CityModelExample example = new CityModelExample(); example.setDistinct( false ); example.setOrderByClause( "id" ); example.createCriteria().andIdBetween( 1, 3 ); List <CityModel> cityList = cityModelMapper.selectByExample(example); for (CityModel cityModel : cityList) { System.out.println( "id:" + cityModel.getId() + "\n" + "name:" + cityModel.getCityName() + "\n" ); } fail( "Not yet implemented" ); } @Test public void testSelectByPrimaryKey() { CityModel cityModel = cityModelMapper.selectByPrimaryKey(8 ); System.out.println( "查詢到一個city" + cityModel.getCityName()); Assert.assertTrue( null != cityModel); } @Test public void testUpdateByExampleSelective() { fail( "Not yet implemented" ); } @Test public void testUpdateByExample() { fail( "Not yet implemented" ); } @Test public void testUpdateByPrimaryKeySelective() { fail( "Not yet implemented" ); } @Test public void testUpdateByPrimaryKey() { CityModel cityModel = new CityModel(); int i = 8 ; cityModel.setId(i); cityModel.setCityName( "updaet" + i); cityModel.setCityCode(i); int flag = cityModelMapper.updateByPrimaryKey(cityModel); session.commit(); System.out.println( "返回值:" + flag); System.out.println( "update一個city id " + i); Assert.assertTrue(flag > 0 ); } @After public void tearDown() throws Exception { } }
6: 用到的sql
DROP TABLE IF EXISTS `tab_city`; CREATE TABLE `tab_city` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `city_name` varchar(255) DEFAULT NULL COMMENT '城市名稱', `city_code` int(11) NOT NULL COMMENT '用三位數字表示 例如 001 代表朝陽', `is_use` int(11) DEFAULT NULL COMMENT '是否有效', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COMMENT='城市代碼表';
完。
?
java_model_dao_自動生成_generator-mybatis-generator-1.3.2 基于maven插件
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
