手记

gradle+ hibernate5.1构建项目


hibernate5.1, 用gradle构建

因为之前遇到Unknown Entity,在其他的网站上都说是,cfg.xml 和POJO 出错,但是我的已经确认没有错误,于是就去stackoverflow上找到了答案。下面和大家分享一下自己的解决办法。

另:如果有关于Gradle怎么构建的问题可以参考本人写的第一篇文章

Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。

  1. 通过gradle添加hibernate的jar包
    build.gradle文件内容(关于如何找jar包之前已经讲解过,不再赘述)
/*
 * This build file was auto generated by running the Gradle 'init' task
 * by 'zhang' at '16-3-7 上午10:33' with Gradle 2.11
 *
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/2.11/userguide/tutorial_java_projects.html
 */

// Apply the java plugin to add support for Java
apply plugin: 'java'
apply plugin:'war'
//apply plugin:'jetty'
//apply from: 'gretty.plugin'
//apply from: 'https://raw.github.com/akhikhl/gretty/master/pluginScripts/gretty.plugin'
// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
  compile 'org.slf4j:slf4j-api:1.7.14',
  'org.hibernate:hibernate-core:5.1.0.Final','org.hibernate:hibernate-c3p0:5.1.0.Final','org.hibernate:hibernate-entitymanager:5.1.0.Final','org.hibernate:hibernate-ehcache:5.1.0.Final',
  'mysql:mysql-connector-java:5.1.38',
  'com.mchange:mchange-commons-java:0.2.11'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile 'junit:junit:4.12'
}
    tasks.withType(JavaCompile) {
    options.encoding = "UTF-8"
}

//gretty {  
 //   port = 8090  
  //  contextPath ="/${project.name}"  
  //  servletContainer = 'tomcat8'
  //  debugPort = 5005      // default
 //     debugSuspend = true   // default
//}

重点在寻找上,而不是直接【ctrl+c】【ctrl+v】。
填写好之后,进行build,这个过程很慢,因为要下载相关的jar包。等等等-------等下去,直到build successful。

  1. 创建【hibernate.cfg.xml】文件
    此文件需要放置在【resources】目录下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory >
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/strutshibernate?useUncode=true&characterEncoding=UTF-8</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">123456</property>
  <property name="hibernate.default_schema">strutshibernate</property>
  <property name="hibernate.current_session_context_class">thread</property>
  <property name="hibernate.connection.pool.size">20</property>    
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.min_size">1</property>
  <property name="hibernate.c3p0.timeout">5000</property>
  <property name="hibernate.c3p0.max_statements">100</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>
  <property name="hibernate.c3p0.acquire_increment">2</property>
  <property name="hibernate.c3p0.validate">true</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <property name="hibernate.connection.autocommit">false</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.format_sql">true</property>
  <mapping class="Entity.Users" />
   <mapping class="Entity.Students" />
 </session-factory>
</hibernate-configuration>

重点两个地方①数据库的链接②配置【mapping class】class的名称为【包.类】

  1. 创建PO类
package Entity;

import javax.persistence.*;
@Entity
@Table(name="users")
public class Users {
    public Users() {
    }
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    @Column(name="username")
    private String username;
    private String password;
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "Users [id=" + id + ", username=" + username + ", password=" + password + "]";
    }

}

PO=POJO+注解
此PO一定要有满足的条件:①类的属性有【get,set】方法②具有无参的构造方法(如果不知道什么叫构造方法的话,慕课网上有教程,自己去复习一下。OK?)③要有【@Entity】和【@Id】注解;④当导入注解包的时候一定要使用jpa的注解【import javax.persistence.*;】,千万不要导错包了。

  1. 创建Session进行数据持久化。
package Test;

import java.util.EnumSet;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.junit.Test;

import Entity.Users;

public class TestMain {
    public static void main(String[] arg){
         try {
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        SessionFactory sessionFactory = new MetadataSources( serviceRegistry ).buildMetadata().buildSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction transaction=session.beginTransaction();
        Users users=new Users();
        users.setId(2);
        session.save(users);
        transaction.commit();
        session.close();
        sessionFactory.close();
         }catch(Throwable th){
                System.err.println("Init SessionFactory creation failed" );
                System.err.println(th);
                throw new ExceptionInInitializerError(th);
         }finally {

        }
    }
    @Test
    public void testSchemaExport(){
        ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().configure().build();
        Metadata metadata=new MetadataSources(serviceRegistry).buildMetadata();
        SchemaExport export=new SchemaExport();
        export.create(EnumSet.of(TargetType.DATABASE), metadata);
        }

}

在此说明,此方法作者仅在hibernate5.1上有过测试,如果使用其他版本,不能保证能够正确运行。
说明两点:①【SchemaExport】的使用参考[Young++ workspace]的博文。②【SessionFactory 】的使用。另:本人也回复其他Unknown Entity的问题[链接描述]

  1. 运行Main即可
com.mchange.v2.cfg.DelayedLogItem [ level -> FINE, text -> "The configuration file for resource identifier '/mchange-commons.properties' could not be found. Skipping.", exception -> null]
com.mchange.v2.cfg.DelayedLogItem [ level -> FINE, text -> "The configuration file for resource identifier 'hocon:/reference,/application,/' could not be found. Skipping.", exception -> null]
Hibernate: 
    insert 
    into
        users
        (password, username) 
    values
        (?, ?)
14:17:57,762 TRACE BasicBinder:53 - binding parameter [1] as [VARCHAR] - [null]
 14:17:57,765 TRACE BasicBinder:53 - binding parameter [2] as [VARCHAR] - [null]
  1. 结束语
    小伙伴们,加油,遇到问题的时候,一定要去网上找找,说不定会有意外惊喜,有的时候,慕课网上的文章也是很不错的。谢谢!
8人推荐
随时随地看视频
慕课网APP