精华内容
下载资源
问答
  • 在Dao层,通过数据库表反向生成,可以节省我们很多的精力,把更多的精力投入复杂的业务中。数据库表反向生成,指的是通过数据库如mysql中的库表schema生成dao层读写表的基础代码,包括model(entity)和dao(mapper)。...

    在Dao层,通过数据库表反向生成,可以节省我们很多的精力,把更多的精力投入复杂的业务中。

    数据库表反向生成,指的是通过数据库如mysql中的库表schema生成dao层读写表的基础代码,包括model(entity)和dao(mapper)。

    在本文中我先介绍java中mybatis-generator的反向生成。我们在下一篇文章中会介绍django中ORM的反向生成。

    mybatis-generator的反向生成有两种方式

    1)源码打包生成mybatis-generator.jar,通过执行jar来生成代码,然后把代码拷贝到工程

    2)直接跟编辑器集成,例如IDEA。

    我们只说明第二种方式。

    1、在IDEA中创建一个maven工程

    2、在maven工程的pom文件中添加mybatis-generator-maven-plugin插件

    org.mybatis.generator

    mybatis-generator-maven-plugin

    1.3.2

    true

    true

    3、在src/main/resources目录下创建两个配置文件,generatorConfig.xml和generator.properties

    generatorConfig.xml文件

    内容请看注释,

    /p>

    PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

    "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

    generator.properties文件

    这个主要配置的是你的驱动程序和数据库链接,mybatis将去配置的数据库中扫描要生成的表。

    jdbc.driverLocation=/Users/didi/.m2/repository/mysql/mysql-connector-java/5.1.40/mysql-connector-java-5.1.40.jar

    jdbc.driverClass=com.mysql.jdbc.Driver

    jdbc.connectionURL=jdbc:mysql://localhost:3306/jazz?useUnicode=true&characterEncoding=utf-8

    jdbc.userId=root

    jdbc.password=123456

    4、在IDEA中添加Run选项,使用mybatis-generator-maven-plugin

    18404f0d3b6c49e9f5011b486efd59c1.png

    配置如下

    1)Name写generator会在run菜单生成一个名叫generator的选项;

    2)CommandLine写要执行的命令,mybatis-generator:generate  -e

    3)working directory写你pom所在的工程,我这里是区分模块开发的,所以在dao模块下。

    e8445c7ff45d67e712ebc520a7624eb4.png

    5、run -> generator执行

    这样就会生成对应的代码了

    我两张表的建表语句如下:

    CREATE TABLE`hiveTable` (

    `id`int(100) NOT NULL AUTO_INCREMENT COMMENT '库表唯一Id',

    `dbName`VARCHAR(100) COMMENT '库名',

    `tableName`VARCHAR(100) COMMENT '表名',

    `location`VARCHAR(500) COMMENT '路径',

    `createTime`DATETIME COMMENT '创建时间',

    `updateTime`DATETIME COMMENT '更新时间',PRIMARY KEY(`id`)

    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;CREATE TABLE`hiveLocation` (

    `id`int(100) NOT NULL AUTO_INCREMENT COMMENT '路径唯一Id',

    `location`VARCHAR(500) COMMENT '路径',

    `size`INT(10) COMMENT '大小',

    `createTime`DATETIME COMMENT '创建时间',

    `updateTime`DATETIME COMMENT '更新时间',PRIMARY KEY(`id`)

    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

    生成的代码如图

    713009a7a6ee3a432226426864d50793.png

    我们展示一些生成的代码:

    HiveTable.java

    packagecom.xiaoju.dqa.jazz.dao.model;importjava.util.Date;public classHiveTable {/*** This field was generated by MyBatis Generator.

    * This field corresponds to the database column hiveTable.id

    *

    * @mbggenerated*/

    privateInteger id;/*** This field was generated by MyBatis Generator.

    * This field corresponds to the database column hiveTable.dbName

    *

    * @mbggenerated*/

    privateString dbname;/*** This field was generated by MyBatis Generator.

    * This field corresponds to the database column hiveTable.tableName

    *

    * @mbggenerated*/

    privateString tablename;/*** This field was generated by MyBatis Generator.

    * This field corresponds to the database column hiveTable.location

    *

    * @mbggenerated*/

    privateString location;/*** This field was generated by MyBatis Generator.

    * This field corresponds to the database column hiveTable.createTime

    *

    * @mbggenerated*/

    privateDate createtime;/*** This field was generated by MyBatis Generator.

    * This field corresponds to the database column hiveTable.updateTime

    *

    * @mbggenerated*/

    privateDate updatetime;/*** This method was generated by MyBatis Generator.

    * This method corresponds to the database table hiveTable

    *

    * @mbggenerated*/

    publicHiveTable(Integer id, String dbname, String tablename, String location, Date createtime, Date updatetime) {this.id =id;this.dbname =dbname;this.tablename =tablename;this.location =location;this.createtime =createtime;this.updatetime =updatetime;

    }/*** This method was generated by MyBatis Generator.

    * This method returns the value of the database column hiveTable.id

    *

    *@returnthe value of hiveTable.id

    *

    * @mbggenerated*/

    publicInteger getId() {returnid;

    }/*** This method was generated by MyBatis Generator.

    * This method returns the value of the database column hiveTable.dbName

    *

    *@returnthe value of hiveTable.dbName

    *

    * @mbggenerated*/

    publicString getDbname() {returndbname;

    }/*** This method was generated by MyBatis Generator.

    * This method returns the value of the database column hiveTable.tableName

    *

    *@returnthe value of hiveTable.tableName

    *

    * @mbggenerated*/

    publicString getTablename() {returntablename;

    }/*** This method was generated by MyBatis Generator.

    * This method returns the value of the database column hiveTable.location

    *

    *@returnthe value of hiveTable.location

    *

    * @mbggenerated*/

    publicString getLocation() {returnlocation;

    }/*** This method was generated by MyBatis Generator.

    * This method returns the value of the database column hiveTable.createTime

    *

    *@returnthe value of hiveTable.createTime

    *

    * @mbggenerated*/

    publicDate getCreatetime() {returncreatetime;

    }/*** This method was generated by MyBatis Generator.

    * This method returns the value of the database column hiveTable.updateTime

    *

    *@returnthe value of hiveTable.updateTime

    *

    * @mbggenerated*/

    publicDate getUpdatetime() {returnupdatetime;

    }

    }

    HiveTableMapper.java

    packagecom.xiaoju.dqa.jazz.dao.mapper;importcom.xiaoju.dqa.jazz.dao.model.HiveTable;import org.apache.ibatis.annotations.*;

    @Mapperpublic interfaceHiveTableMapper {/*** This method was generated by MyBatis Generator.

    * This method corresponds to the database table hiveTable

    *

    * @mbggenerated*/@Delete({"delete from hiveTable","where id = #{id,jdbcType=INTEGER}"})intdeleteByPrimaryKey(Integer id);/*** This method was generated by MyBatis Generator.

    * This method corresponds to the database table hiveTable

    *

    * @mbggenerated*/@Insert({"insert into hiveTable (id, dbName, ","tableName, location, ","createTime, updateTime)","values (#{id,jdbcType=INTEGER}, #{dbname,jdbcType=VARCHAR}, ","#{tablename,jdbcType=VARCHAR}, #{location,jdbcType=VARCHAR}, ","#{createtime,jdbcType=TIMESTAMP}, #{updatetime,jdbcType=TIMESTAMP})"})intinsert(HiveTable record);/*** This method was generated by MyBatis Generator.

    * This method corresponds to the database table hiveTable

    *

    * @mbggenerated*/

    intinsertSelective(HiveTable record);/*** This method was generated by MyBatis Generator.

    * This method corresponds to the database table hiveTable

    *

    * @mbggenerated*/@Select({"select","id, dbName, tableName, location, createTime, updateTime","from hiveTable","where id = #{id,jdbcType=INTEGER}"})

    @ResultMap("BaseResultMap")

    HiveTable selectByPrimaryKey(Integer id);/*** This method was generated by MyBatis Generator.

    * This method corresponds to the database table hiveTable

    *

    * @mbggenerated*/

    intupdateByPrimaryKeySelective(HiveTable record);/*** This method was generated by MyBatis Generator.

    * This method corresponds to the database table hiveTable

    *

    * @mbggenerated*/@Update({"update hiveTable","set dbName = #{dbname,jdbcType=VARCHAR},","tableName = #{tablename,jdbcType=VARCHAR},","location = #{location,jdbcType=VARCHAR},","createTime = #{createtime,jdbcType=TIMESTAMP},","updateTime = #{updatetime,jdbcType=TIMESTAMP}","where id = #{id,jdbcType=INTEGER}"})intupdateByPrimaryKey(HiveTable record);

    }

    HiveTableMapper.xml

    id, dbName, tableName, location, createTime, updateTime

    insert into hiveTable

    id,

    dbName,

    tableName,

    location,

    createTime,

    updateTime,

    #{id,jdbcType=INTEGER},

    #{dbname,jdbcType=VARCHAR},

    #{tablename,jdbcType=VARCHAR},

    #{location,jdbcType=VARCHAR},

    #{createtime,jdbcType=TIMESTAMP},

    #{updatetime,jdbcType=TIMESTAMP},

    update hiveTable

    dbName = #{dbname,jdbcType=VARCHAR},

    tableName = #{tablename,jdbcType=VARCHAR},

    location = #{location,jdbcType=VARCHAR},

    createTime = #{createtime,jdbcType=TIMESTAMP},

    updateTime = #{updatetime,jdbcType=TIMESTAMP},

    where id = #{id,jdbcType=INTEGER}

    想让xml文件生效,你可以在创建数据源的时候加入xml文件的路径

    例如其中的bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mapper/*.xml"));

    packagecom.xiaoju.dqa.jazz.dao.configuration;importorg.apache.ibatis.session.SqlSessionFactory;importorg.mybatis.spring.SqlSessionFactoryBean;importorg.mybatis.spring.SqlSessionTemplate;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;importorg.springframework.jdbc.datasource.DataSourceTransactionManager;importjavax.sql.DataSource;

    @Configuration

    @MapperScan(basePackages= "com.xiaoju.dqa.jazz.dao.mapper", sqlSessionTemplateRef = "jazzSqlSessionTemplate")public classJazzDataSource {

    @Bean(name= "jazzData")

    @ConfigurationProperties(prefix= "spring.datasource.jazz")

    @PrimarypublicDataSource jazzData() {returnDataSourceBuilder.create().build();

    }

    @Bean(name= "jazzSqlSessionFactory")

    @Primarypublic SqlSessionFactory jazzSqlSessionFactory(@Qualifier("jazzData") DataSource dataSource) throwsException {

    SqlSessionFactoryBean bean= newSqlSessionFactoryBean();

    bean.setDataSource(dataSource);

    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis-mapper/*.xml"));returnbean.getObject();

    }

    @Bean(name= "jazzTransactionManager")

    @Primarypublic DataSourceTransactionManager jazzTransactionManager(@Qualifier("jazzData") DataSource dataSource) {return newDataSourceTransactionManager(dataSource);

    }

    @Bean(name= "jazzSqlSessionTemplate")

    @Primarypublic SqlSessionTemplate jazzSqlSessionTemplate(@Qualifier("jazzSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throwsException {return newSqlSessionTemplate(sqlSessionFactory);

    }

    }

    展开全文
  • 一、通过MyEclipse生成Hibernate类文件和hbm.xml文件,或者annotation文件 (转载孙宇老师的文章) 二、Mybatis生成实体类和配置文件: myeclipse下生成实体类和map配置文件: 1、新建一个maven工程 2、修改...

    一、通过MyEclipse生成Hibernate类文件和hbm.xml文件,或者annotation文件    (转载孙宇老师的文章)

    二、Mybatis生成实体类和配置文件:

    myeclipse下生成实体类和map配置文件:

    1、新建一个maven工程

    2、修改pom.xml文件

    <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.jacksoft.mybatis</groupId>
      <artifactId>mybatis-generator</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      
      <properties>
        <mybatis-generator.version>1.3.1</mybatis-generator.version>
        <mysql.version>5.1.13</mysql.version>
        <mybatis.version>3.0.3</mybatis.version>
      </properties>
      
      <dependencies>
    
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>${mysql.version}</version>
        </dependency>
      
        <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>${mybatis-generator.version}</version>
        </dependency>
    
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>${mybatis.version}</version>
        </dependency>
      </dependencies>
      
      <build>
        <finalName>mybatis-generator</finalName>
      <plugins>
        <plugin>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-maven-plugin</artifactId>
          <version>${mybatis-generator.version}</version>
          <dependencies>
          <!-- 数据库驱动  -->
            <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>${mysql.version}</version>
            </dependency>
        
          </dependencies>
          <!-- 自动生成 -->
          <executions>
            <execution>
              <id>Generate MyBatis Artifacts</id>
              <goals>
                <goal>generate</goal>
              </goals>
              <configuration>
                <configurationFile>src/main/resources/mysqlGeneratorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
                <jdbcDriver>com.mysql.jdbc.Driver</jdbcDriver>
                <jdbcURL>jdbc:mysql://localhost:3306/springmvc_mybatis</jdbcURL>
                <jdbcUserId>root</jdbcUserId>
                <jdbcPassword></jdbcPassword>
              </configuration>
            </execution>
          </executions>
        </plugin>
      
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <configuration>
            <source>1.7</source>
            <target>1.7</target>
            <encoding>UTF-8</encoding>
          </configuration>
        </plugin>
    
        </plugins>
      </build>
    </project>

    3、添加mysqlGeneratorConfig.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>
    
        <context id="mysqlTables" targetRuntime="MyBatis3">
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/springmvc_mybatis" userId="root"
                password="" />
    
            <!-- 指定生成的类型为java类型,避免数据库中number等类型字段 -->
            <javaTypeResolver>
                <property name="forceBigDecimals" value="false" />
            </javaTypeResolver>
    
            <!-- 生成model模型,对应的包,存放位置可以指定具体的路径,如/ProjectName/src,也可以使用MAVEN来自动生成 -->
            <javaModelGenerator targetPackage="com.wjy.model"
                targetProject="MAVEN">
                <property name="enableSubPackages" value="true" />
                <property name="trimStrings" value="true" />
            </javaModelGenerator>
    
            <!--对应的xml mapper文件 -->
            <sqlMapGenerator targetPackage="com.wjy.mapper"
                targetProject="MAVEN">
                <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
    
            <!-- 对应的dao接口 -->
            <javaClientGenerator type="XMLMAPPER"
                targetPackage="com.wjy.dao" targetProject="MAVEN">
                <property name="enableSubPackages" value="true" />
            </javaClientGenerator>
    
    
            <table tableName="user_info" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
            <table tableName="course_info" domainObjectName="Course" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
            <table tableName="course_user_info" domainObjectName="CourseUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
        </context>
    </generatorConfiguration>

    4、生成

     

     

    去target目录下看看  是否都已经出来了:

    转载于:https://www.cnblogs.com/cac2020/p/5222208.html

    展开全文
  • import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import ...

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.sql.ResultSetMetaData;

    import java.sql.SQLException;

    import com.onedear.util.database.DataBaseType;

    /**

    * 数据库工具类

    *

    * @author onedear

    * @data:2010-10-21 下午06:12:39

    */

    public class DBUtil {

    public static final int SQLSERVER = 1;

    public static final int MYSQL = 2;

    public static final int ORACLE = 3;

    private static final String LINE = "\r\n";

    private static final String TAB = "\t";

    /**

    * 用于调试,懒得写相应的参数

    *

    * @return

    * @throws SQLException

    * @throws ClassNotFoundException

    */

    public static Connection getConnection() throws ClassNotFoundException, SQLException {

    return getConnection("192.168.0.161:1997", "ETForMonitor_V2", "sa",

    "password", DBUtil.SQLSERVER);

    }

    /**

    *

    * 通过jdbc获取相应的数据库链接connection

    *

    * @param ipport

    * ip+port ,eg.: 192.168.0.161:1997

    * @param dbName

    * databaseName ,eg. : ETForMonitor_V2

    * @param username

    * eg.:sa

    * @param password

    * eg. :password

    * @param type

    * 请看本类的静态变量

    * @return

    * @throws ClassNotFoundException

    * @throws SQLException

    */

    public static Connection getConnection(String ipport, String dbName,

    String username, String password, int type)

    throws ClassNotFoundException, SQLException {

    String jdbcString = null;

    if (type == SQLSERVER) {

    jdbcString = "jdbc:jtds:sqlserver://" + ipport + ";databaseName="

    + dbName;

    Class.forName("net.sourceforge.jtds.jdbc.Driver");

    } else if (type == MYSQL) {

    jdbcString = "jdbc:mysql://" + ipport + "/" + dbName;

    Class.forName("org.gjt.mm.mysql.Driver");

    } else if (type == ORACLE) {

    jdbcString = "jdbc:oracle:thin:@" + ipport + ":" + dbName;

    Class.forName("oracle.jdbc.driver.OracleDriver");

    }

    Connection connection = null;

    connection = DriverManager

    .getConnection(jdbcString, username, password);

    return connection;

    }

    /**

    * 数据库表生成相应的java类,生成规则

    * 类名= 表名(第一个字母大写)

    * 属性名= 数据库列名

    * get/set方法 = 根据标准生成

    * 其中生成的基本类型均为包装类,例如Integer , Long , Boolean , String

    * @param connection

    * @param tableName

    * @param dbType

    * @param path

    * @param isCreateFile

    * @return

    * @throws SQLException

    */

    public static String table2pojo(Connection connection, String tableName,

    int dbType, String path , boolean isCreateFile) throws SQLException {

    String sql = "select * from " + tableName + " where 1 <> 1";

    PreparedStatement ps = null;

    ResultSet rs = null;

    ps = connection.prepareStatement(sql);

    rs = ps.executeQuery();

    ResultSetMetaData md = rs.getMetaData();

    int columnCount = md.getColumnCount();

    StringBuffer sb = new StringBuffer();

    tableName = tableName.substring(0, 1).toUpperCase() +tableName.subSequence(1, tableName.length());

    sb.append("public class " + tableName + " {");

    sb.append(LINE);

    for (int i = 1; i <= columnCount; i++) {

    sb.append(TAB);

    sb.append("private "

    + DataBaseType.getPojoType(md.getColumnTypeName(i)) + " "

    + md.getColumnName(i) + ";");

    // System.out.println("name : " + md.getColumnName(i) +

    // " , type :"

    // + md.getColumnTypeName(i));

    sb.append(LINE);

    }

    for (int i = 1; i <= columnCount; i++) {

    sb.append(TAB);

    String pojoType = DataBaseType.getPojoType(md.getColumnTypeName(i));

    String columnName = md.getColumnName(i);

    String getName = null;

    String setName = null;

    if (columnName.length() > 1) {

    getName = "public "+pojoType+" get" + columnName.substring(0, 1).toUpperCase()

    + columnName.substring(1, columnName.length()) + "() {";

    setName = "public void set" + columnName.substring(0, 1).toUpperCase()

    + columnName.substring(1, columnName.length()) + "("

    + pojoType + " " + columnName + ") {";

    } else {

    getName = "public get" + columnName.toUpperCase() + "() {";

    setName = "public set" + columnName.toUpperCase() + "(" + pojoType

    + " " + columnName + ") {";

    }

    sb.append(LINE).append(TAB).append(getName);

    sb.append(LINE).append(TAB).append(TAB);

    sb.append("return " + columnName +";");

    sb.append(LINE).append(TAB).append("}");

    sb.append(LINE);

    sb.append(LINE).append(TAB).append(setName);

    sb.append(LINE).append(TAB).append(TAB);

    sb.append("this." + columnName + " = " + columnName +";" );

    sb.append(LINE).append(TAB).append("}");

    sb.append(LINE);

    }

    sb.append("}");

    System.out.println(sb.toString());

    if(isCreateFile)

    FileUtils.stringToFile(null,tableName +".java" , sb.toString());

    return null;

    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {

    Connection con = getConnection();

    table2pojo(con, "PlayBackVisitorControl", DBUtil.SQLSERVER, "" , true);

    }

    }

    展开全文
  • 于是就想到通过数据库反向生成java类,但没有myeclipse又不懂生成,于是手动写了一个大概的方法,暂时仅仅在sqlserver测试通过,对于包名跟引用类就没写了,把代码复制到eclipse直接ctrl+shift+o就导入了 ...
    下午要根据数据库的一个表写一个pojo,那个累啊,80列名。写了大概10列就没心情写了。于是就想到通过数据库反向生成java类,但没有myeclipse又不懂生成,于是手动写了一个大概的方法,暂时仅仅在sqlserver测试通过,对于包名跟引用类就没写了,把代码复制到eclipse直接ctrl+shift+o就导入了




    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;

    import com.onedear.util.database.DataBaseType;

    /**
    * 数据库工具类
    *
    * @author onedear
    * @data:2010-10-21 下午06:12:39
    */
    public class DBUtil {

    public static final int SQLSERVER = 1;
    public static final int MYSQL = 2;
    public static final int ORACLE = 3;
    private static final String LINE = "\r\n";
    private static final String TAB = "\t";

    /**
    * 用于调试,懒得写相应的参数
    *
    * @return
    * @throws SQLException
    * @throws ClassNotFoundException
    */
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
    return getConnection("192.168.0.161:1997", "ETForMonitor_V2", "sa",
    "password", DBUtil.SQLSERVER);
    }

    /**
    *
    * 通过jdbc获取相应的数据库链接connection
    *
    * @param ipport
    * ip+port ,eg.: 192.168.0.161:1997
    * @param dbName
    * databaseName ,eg. : ETForMonitor_V2
    * @param username
    * eg.:sa
    * @param password
    * eg. :password
    * @param type
    * 请看本类的静态变量
    * @return
    * @throws ClassNotFoundException
    * @throws SQLException
    */
    public static Connection getConnection(String ipport, String dbName,
    String username, String password, int type)
    throws ClassNotFoundException, SQLException {
    String jdbcString = null;
    if (type == SQLSERVER) {
    jdbcString = "jdbc:jtds:sqlserver://" + ipport + ";databaseName="
    + dbName;
    Class.forName("net.sourceforge.jtds.jdbc.Driver");
    } else if (type == MYSQL) {
    jdbcString = "jdbc:mysql://" + ipport + "/" + dbName;
    Class.forName("org.gjt.mm.mysql.Driver");
    } else if (type == ORACLE) {
    jdbcString = "jdbc:oracle:thin:@" + ipport + ":" + dbName;
    Class.forName("oracle.jdbc.driver.OracleDriver");
    }

    Connection connection = null;
    connection = DriverManager
    .getConnection(jdbcString, username, password);
    return connection;
    }

    /**
    * 数据库表生成相应的java类,生成规则
    * 类名= 表名(第一个字母大写)
    * 属性名= 数据库列名
    * get/set方法 = 根据标准生成
    * 其中生成的基本类型均为包装类,例如Integer , Long , Boolean , String
    * @param connection
    * @param tableName
    * @param dbType
    * @param path
    * @param isCreateFile
    * @return
    * @throws SQLException
    */
    public static String table2pojo(Connection connection, String tableName,
    int dbType, String path , boolean isCreateFile) throws SQLException {
    String sql = "select * from " + tableName + " where 1 <> 1";
    PreparedStatement ps = null;
    ResultSet rs = null;
    ps = connection.prepareStatement(sql);
    rs = ps.executeQuery();
    ResultSetMetaData md = rs.getMetaData();
    int columnCount = md.getColumnCount();

    StringBuffer sb = new StringBuffer();
    tableName = tableName.substring(0, 1).toUpperCase() +tableName.subSequence(1, tableName.length());
    sb.append("public class " + tableName + " {");
    sb.append(LINE);

    for (int i = 1; i <= columnCount; i++) {
    sb.append(TAB);
    sb.append("private "
    + DataBaseType.getPojoType(md.getColumnTypeName(i)) + " "
    + md.getColumnName(i) + ";");
    // System.out.println("name : " + md.getColumnName(i) +
    // " , type :"
    // + md.getColumnTypeName(i));
    sb.append(LINE);
    }

    for (int i = 1; i <= columnCount; i++) {
    sb.append(TAB);

    String pojoType = DataBaseType.getPojoType(md.getColumnTypeName(i));
    String columnName = md.getColumnName(i);
    String getName = null;
    String setName = null;
    if (columnName.length() > 1) {
    getName = "public "+pojoType+" get" + columnName.substring(0, 1).toUpperCase()
    + columnName.substring(1, columnName.length()) + "() {";
    setName = "public void set" + columnName.substring(0, 1).toUpperCase()
    + columnName.substring(1, columnName.length()) + "("
    + pojoType + " " + columnName + ") {";
    } else {
    getName = "public get" + columnName.toUpperCase() + "() {";
    setName = "public set" + columnName.toUpperCase() + "(" + pojoType
    + " " + columnName + ") {";
    }

    sb.append(LINE).append(TAB).append(getName);
    sb.append(LINE).append(TAB).append(TAB);
    sb.append("return " + columnName +";");
    sb.append(LINE).append(TAB).append("}");
    sb.append(LINE);
    sb.append(LINE).append(TAB).append(setName);
    sb.append(LINE).append(TAB).append(TAB);
    sb.append("this." + columnName + " = " + columnName +";" );
    sb.append(LINE).append(TAB).append("}");
    sb.append(LINE);

    }
    sb.append("}");

    System.out.println(sb.toString());

    if(isCreateFile)
    FileUtils.stringToFile(null,tableName +".java" , sb.toString());
    return null;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    Connection con = getConnection();
    table2pojo(con, "PlayBackVisitorControl", DBUtil.SQLSERVER, "" , true);

    }


    }






    import java.util.HashMap;
    import java.util.Map;
    import java.util.StringTokenizer;

    /**
    *
    * @author onedear
    * @data:2010-11-15 下午07:54:23
    */
    public class DataBaseType {
    private static Map<String , String> map ;

    static {
    map = new HashMap<String , String>();
    map.put("varchar", "String");
    map.put("int", "Integer");
    map.put("datetime", "Date");
    map.put("nvarchar", "String");
    map.put("char", "String");
    map.put("uniqueidentifier", "String");
    map.put("bigint", "Long");
    map.put("tinyint", "Boolean");
    }

    public static String getPojoType(String dataType ) {
    String tmp = dataType.toLowerCase();
    StringTokenizer st = new StringTokenizer(tmp);
    return map.get(st.nextToken()) ;
    }
    }

    展开全文
  • MyEclipse JavaPersistence进行了上面的 操作后会出现一个视图DB Brower:MyEclipse Derby,点击右键新建new一个在出现的面板Database Driver中,Drivertemplate中选择Oracle(ThinDriver)这里以oracle软件为例,如果是...
  • hibernate通过数据库表反向生成实体类  (2013-11-20 10:08:08) 转载▼ 标签: hibernate 反向生成 it 分类: Hibernate 步骤一: window--&gt;open Perspective--&...
  • window-->open Perspective-->MyEclipse Java Persistence 进行了上面的 操作后会出现一个视图DB Brower:MyEclipse Derby, 点击右键新建new一个在出现的面板Database Driver中,Driver ...
  • import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; ...
  • 一:下载jar包下载 mysql-connector-java-5.1.17.jar jar包来源:51cto、csdn,或者直接从网上下载二:generatorConfig.xml 文件存放路径:在项目工程下的:src/main/resources&lt;?xml version="1.0"...
  • 在Dao层,通过数据库表反向生成,可以节省我们很多的精力,把更多的精力投入复杂的业务中。 数据库表反向生成,指的是通过数据库如mysql中的库表schema生成dao层读写表的基础代码,包括model(entity)和dao(mapper)...
  • 需要工具 PD(v11) + 数据库设计模型1、建立ODBC,从数据库中将导入到 PD 中。2、PD 菜单 TOOLS generate object-oriented 3、在左边的菜单中出现 classes 文件夹,选择 对应的类 右键 attributes 并选择 add ...
  • mybatis-generator反向生成Java代码通过链接数据库表反向生成dao和实体以及xml等
  • 最近整理 一个项目,原先的项目是用的oracle,然而新的...要在项目中写实体类由于太多,并且防止写的实体类与数据库有出入,所以就找想:在eclipse中从数据自动生成hibernate的java实体类。最终生成成功,在此做...
  • 平时开发中总是要根据别人建立好的数据库生成对应的实体,当然如果使用hibernate也可以用它自身的工具去生成或者通过实体反向生成对应的表结构,但是大部分都是根据数据库表去生成实体的,为了避免重复干这种活,...
  • 有一天,公司的项目经理急匆匆的跑过来跟我说,公司招了一个新研发,不小心把数据库给删了,这个数据库还没来得及备份,咋办啊,没办法,只能通过mapper文件反向生成表结构了,mybatis里通过表结构生成mapper.xml...
  • 在上节课中我们介绍了在SpringBoot中如何集成...那么此时,如果能够通过插件完成数据库表结构到代码的生成,那将是一件非常爽的事。 本篇文章就为大家介绍这么一款插件。 插件集成 关于Spring Boot集成Mybatis的部分...
  • hibernate反向生成图例

    2013-03-19 10:26:16
    通过数据库表、用JAVA生成实体类的步骤。
  • java中mybatis-...通过数据库中存在的生成model 对于mysql数据库,通过代码,反向生成 sqlalchemy 的 model的方法为 sqlacodegen --tables your_table 'myslqurl' sqlacodegen --tables third_api ‘mysql...
  • 那么如果太多的话,难免会很麻烦,所以mybatis官方提供了一个逆向工程,可以针对单自动生成mybatis执行所需要的代码,一般在开发中,常用的逆向工程方式是通过数据库表生成代码。下图为逆向工程依赖的jar包my....
  • mybatis可以通过数据库表直接替我们生成模型类和mappper文件。 这里说一下怎么配置,尤其是如何加上中文注释。当前前提是数据表和字段有中文注释。 比如这样的: 下面配置自动生成模型类和mapper类还有mapper的xml...
  • 在Hibernate中反向这个表生成Uers.java,小弟的问题是: 1.反向后这3条记录常驻内存不? 2.新建一个UsersTest.java在main方法中测试, Users us=new Users(1); 这个us此时应该算一个什么?我通过 system.out.print...
  • 通过数据库中的,使用 MyEclipse2017的反向生成工具-->hibernate反转引擎引擎(MyEclipse2017自带的插件) 来反转生成实体类和对应的映射文件 文章目录 Java视图 Hibernate视图 eclipse ...
  • Java数据库编程宝典2

    2008-09-28 11:11:49
    3.3.1 创建、取消、更改数据库 3.3.2 创建、更改和取消视图 3.4 数据处理语言 3.4.1 INSERT语句 3.4.2 UPDATE语句 3.4.3 DELETE语句 3.5 数据查询语言 3.5.1 SELECT语句 3.5.2 WHERE子句 3.5.3 SQL...

空空如也

空空如也

1 2 3 4 5 6
收藏数 107
精华内容 42
关键字:

java通过数据库表反向生成

java 订阅