为什么使用代码生成器?
1 .直接生成代码,减少手工开发工作量;
2. 生成的代码格式无误,避免手工编写中错误的可能性;
问题:
你要明白mybatis的ORMAPPING 关系(扯上的)......
<?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驱动的jar包地址 -->
<classPathEntry location="D:\dbjars\mysql\mysql-connector-java-5.1.26.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 是否去除自动生成的注释 true:是,false:否 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://IP地址:3306/common_db" userId="root" password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!---Java 实体的生成 -->
<!-- targetProject:自动生成代码的位置 -->
<javaModelGenerator targetPackage="com.peit.api.model"
targetProject="D:\dbjars\mysql\java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="fasle"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="false"/>
</javaModelGenerator>
<!--sqlMapper XML文件的生成信息,包括生成路径等 -->
<sqlMapGenerator targetPackage="sqlmap"
targetProject="D:\dbjars\mysql\resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!--应用接口的生成信息 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.peit.api.dao" implementationPackage="com.peit.api.dao.impl"
targetProject="D:\dbjars\mysql\java">
<property name="enableSubPackages" value="false"/>
<property name="methodNameCalculator" value="extended"/>
</javaClientGenerator>
<!-- tableName:用于自动生成代码的数据库表;domainObjectName:对应于数据库表的javaBean类名 -->
<table schema="user_points" tableName="user_points" domainObjectName="UserPoints" enableInsert="true"
enableSelectByPrimaryKey="true"
enableSelectByExample="false"
enableUpdateByPrimaryKey="true"
enableDeleteByPrimaryKey="true"
enableDeleteByExample="false"
enableCountByExample="false"
enableUpdateByExample="false" modelType="flat" >
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
</table>
</context>
</generatorConfiguration>
缺点:只能生成基于主键相关的CRUD的SQL语句;
(CRUD是指在做计算处理时的增加(Create)、读取(Read)、更新(Update)和删除(Delete)几个单词的首字母简写)
科普:
什么是mybatis
MyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架。
MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。
MyBatis使用简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plan Old Java Objects,普通的Java对象)映射成数据库中的记录.
orm工具的基本思想
1. 从配置文件(通常是XML配置文件中)得到 sessionfactory.
2. 由sessionfactory 产生 session
3. 在session 中完成对数据的增删改查和事务提交等.
4. 在用完之后关闭session 。
5. 在java 对象和 数据库之间有做mapping 的配置文件,也通常是xml 文件。