Hibernate在cfg.buildSessionFactory()突然挂起

时间:2016-01-03 02:54:46

标签: java hibernate

我已经开始学习Hibernate并且正在学习一些教程。 在尝试其中一个例子时,我无法继续前进,无法看到或理解究竟发生了什么...... ....

这是我的代码....(我有一个正常的cfg文件) 我的班级如下:

UserDetails.java:

 package pack.dto;

 @Entity
 @Table(name = "user_details")

 public class UserDetails {
    @Id
    private int userId;
    private String userName;
    @Temporal(TemporalType.DATE)
    private Date joinedDate;
    @Embedded
    private Address address;
    @Lob
    private String description;
    public Integer age;

    public int getUserId() {
       return userId;
    }

    public void setUserId(int userId) {
       this.userId = userId;
    }

    public String getUserName() {
       return userName;
    }

    public void setUserName(String userName) {
       this.userName = userName;
    }

    public Date getJoinedDate() {
       return joinedDate;
    }

    public void setJoinedDate(Date joinedDate) {
       this.joinedDate = joinedDate;
    }

    public Address getAddress() {
       return address;
    }

    public void setAddress(Address address) {
       this.address = address;
    }

    public String getDescription() {
       return description;
    }

    public void setDescription(String description) {
       this.description = description;
    }

    @Override
      public String toString() {
         return "UserDetails [userId=" + userId + ", userName=" + userName
            + ", joinedDate=" + joinedDate + ", address=" + address
            + ", description=" + description + ", age=" + age + "]";
}

}

我的Address.java类如下所示,我试图用UserDetails类嵌入:

 package pack.dto;
 import javax.persistence.Embeddable;

 @Embeddable
 public class Address {
    private String street;
    private String city;
    private String state;
    private String pinCode;

    public String getStreet() {
       return street;
    }

    public void setStreet(String street) {
       this.street = street;
    }

    public String getCity() {
       return city;
    }

    public void setCity(String city) {
       this.city = city;
    }

    public String getState() {
       return state;
    }

    public void setState(String state) {
       this.state = state;
    }

    public String getPinCode() {
       return pinCode;
    }

    public void setPinCode(String pinCode) {
       this.pinCode = pinCode;
    }


 }

我的cfg文件中的一些重要标签如下:

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernatedb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>

 <property name="hbm2ddl.auto">create</property>
 <!--I have mapped only the userdetails class as Address class is to be embedded -->
<mapping class="pack.dto.UserDetails"/>

我正在使用以下代码对其进行测试:

    UserDetails user = new UserDetails();
    user.setUserId(1);
    user.setUserName("Neeraj");
    user.setDescription("Great Coder");
    user.setJoinedDate(new Date());
    user.age = 24;

    Address addrNeeraj = new Address();
    addrNeeraj.setCity("Pune");
    addrNeeraj.setPinCode("411004");
    addrNeeraj.setState("Maharashtra");
    addrNeeraj.setStreet("KarveRoad");
    user.setAddress(addrNeeraj);

    SessionFactory sessionFactory = new Configuration().configure()
            .buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
    session.clear();
    session.close();
    session.getSessionFactory().close();
    sessionFactory.close();

当我尝试调试此代码时,代码卡在了:

 SessionFactory sessionFactory = new Configuration().configure()
            .buildSessionFactory();

并且从未创建过SessionFactory。 原木卡在了:

  Jan 03, 2016 8:02:20 AM org.hibernate.Version logVersion
  INFO: HHH000412: Hibernate Core {5.0.6.Final}
  Jan 03, 2016 8:02:20 AM org.hibernate.cfg.Environment <clinit>
  INFO: HHH000206: hibernate.properties not found
  Jan 03, 2016 8:02:20 AM org.hibernate.cfg.Environment      buildBytecodeProvider
  INFO: HHH000021: Bytecode provider name : javassist
  Jan 03, 2016 8:02:22 AM       org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
  INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
  Jan 03, 2016 8:02:22 AM   org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
  WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
  Jan 03, 2016 8:02:22 AM   org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/hibernatedb]
  Jan 03, 2016 8:02:22 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  INFO: HHH10001001: Connection properties: {user=root, password=****}
  Jan 03, 2016 8:02:22 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
  INFO: HHH10001003: Autocommit mode: false
  Jan 03, 2016 8:02:22 AM  org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
  INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
  Jan 03, 2016 8:02:23 AM org.hibernate.dialect.Dialect <init>
  INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
  Jan 03, 2016 8:02:24 AM org.hibernate.tool.hbm2ddl.SchemaExport execute
  INFO: HHH000227: Running hbm2ddl schema export
  Hibernate: drop table if exists user_details

日志未进一步Hibernate: drop table if exists user_details。为什么会这样?我的代码有什么问题?为什么没有创建SessionFactory?

3 个答案:

答案 0 :(得分:1)

(1)在构建sessionFactory时,hibernate尝试读取文件名hibernate.cfg.xml,

因此,您的cfg文件名必须与此相同。

下面的

可以是您的cfg文件:

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>

        <mapping class="pack.dto.UserDetails" />
    </session-factory>
</hibernate-configuration>

(2)尝试使用此代码创建sessionFactory,(适用于hibernate版本4.3.x)

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    /**
     * One connection from a DB requires only one instance of sessionFactory in
     * an application.
     * 
     * @return SessionFactory
     */
    private static SessionFactory buildSessionFactory() {
        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .buildServiceRegistry();
        return configuration.buildSessionFactory(serviceRegistry);
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

以下代码保存UserDetails

UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("Neeraj");
user.setDescription("Great Coder");
user.setJoinedDate(new Date());
user.age = 24;

Address addrNeeraj = new Address();
addrNeeraj.setCity("Pune");
addrNeeraj.setPinCode("411004");
addrNeeraj.setState("Maharashtra");
addrNeeraj.setStreet("KarveRoad");
user.setAddress(addrNeeraj);

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();

答案 1 :(得分:0)

U必须将端口放在配置上以创建sessionFactory

<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- port 3306 or whatever u use -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>

答案 2 :(得分:0)

我遇到了类似的问题..在我的情况下重启mysql服务工作..

sudo service mysql restart