mysql - 如何在hibernate的配置文件中拥有多个映射资源?

标签 mysql hibernate

我有 2 个 POJO 的员工和地址以及两个表员工和地址。我首先尝试将地址行添加到数据库中,然后使用之前添加的地址记录的引用添加员工记录。只有当配置文件中有一个映射资源时,我才能添加地址记录。

我的主文件:`package Many2one;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class ManageEmployee {    
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    Session session = null;
    try
    {
        Configuration configuration = new Configuration();            
        configuration.configure("many2one/hibernate.cfg.xml");
        ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sf = configuration.buildSessionFactory(sr);
        session = sf.openSession();
        session.beginTransaction();
        System.out.println("Populating the Database.");
        Address1 address = new Address1("Mogappair","Chennai","Tamilnadu","600107");            
        session.save(address);           
        session.getTransaction().commit();
        System.out.println("Done");
    }catch(HibernateException he){
        System.out.println("Exception Thrown " + he);
    }finally{
        session.flush();
        session.close();
    }

}

}

我的员工 POJO:

package many2one;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name="employee")
public class Employee1 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
public String firstName;
public String lastName;
public int salary;
public Address1 address;

public Employee1(){}

public Employee1(String f_name,String l_name,int sal,Address1 add){
    this.firstName = f_name;
    this.lastName = l_name;
    this.salary = sal;
    this.address = add;
}


public Long getId() {
    return id;
}

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

public String getFirstName(){
    return firstName;
}

public void setFirstName(String f_name){
    this.firstName = f_name;
}

public String getLastName(){
    return lastName;
}

public void setLastName(String l_name){
    this.lastName = l_name;
}

public Address1 getAddress(){
    return address;
}

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


}

我的地址文件

package many2one;

import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name="address")
public class Address1 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
public String streetName;
public String cityName;
public String stateName;
public String zipcode;

public Address1(){}
public Address1(String s_name,String c_name,String st_name,String zipcode){
    this.streetName = s_name;
    this.cityName = c_name;
    this.stateName = st_name;
    this.zipcode = zipcode;
}

public Long getId() {
    return id;
}

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

public String getStreetName() {
    return streetName;
}

public void setStreetName(String s_name) {
    this.streetName = s_name;
}

public String getCityName() {
    return cityName;
}

public void setCityName(String c_name) {
    this.cityName = c_name;
}

public String getStateName() {
    return stateName;
}

public void setStateName(String state_name) {
    this.stateName = state_name;
}

public String getZipcode() {
    return zipcode;
}

public void setZipcode(String zipcode) {
    this.zipcode = zipcode;
}



}

配置文件:

<?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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<!--<mapping resource="many2one/Mapping.hbm.xml"/>-->
<mapping resource="many2one/Address1.hbm.xml"/>
</session-factory>
</hibernate-configuration>

映射文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="many2one.Employee1" table="employee">
<meta attribute="class-description">
  This contains the Employee Details
</meta>    
<id name="id" column="id" type="long">
  <generator class="native"></generator>
</id>
  <property name="firstName" column="first_name" type="string"></property>
  <property name="lastName" column="last_name" type="string"></property>
  <property name="salary" column="salary" type="string"></property>
  <many-to-one name="address" column="address" class="many2one.Address1" not-null="true"/>
  </class>
  <class name="many2one.Address1" table="address">
  <meta attribute="class-description">
      This contains the Address Details
  </meta>
  <id name="id" column="id" type="long">
      <generator class="native"></generator>
  </id>
  <property name="streetName" column="street_name" type="string"></property>
  <property name="cityName" column="city_name" type="string"></property>
  <property name="stateName" column="state_name" type="string"></property>
  <property name="zipcode" column="zipcode" type="string"></property>
  </class>  

  </hibernate-mapping>

我的任务是在数据库中添加一条地址记录,然后使用具有地址引用的员工构造函数添加一条员工记录。当注释掉员工表的映射资源时,我可以添加地址记录,但如果我尝试同时执行这两项操作,则会收到错误。无法获取构造函数错误。

StackTrace:`调试:

Feb 26, 2015 11:19:10 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>

INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
Feb 26, 2015 11:19:11 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.1.Final}
Feb 26, 2015 11:19:11 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 26, 2015 11:19:11 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 26, 2015 11:19:12 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: many2one/hibernate.cfg.xml
Feb 26, 2015 11:19:12 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: many2one/hibernate.cfg.xml
Feb 26, 2015 11:19:12 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: many2one/Mapping.hbm.xml
Feb 26, 2015 11:19:13 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Feb 26, 2015 11:19:15 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Feb 26, 2015 11:19:16 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?zeroDateTimeBehavior=convertToNull]
Feb 26, 2015 11:19:16 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root}
Feb 26, 2015 11:19:16 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Feb 26, 2015 11:19:16 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Feb 26, 2015 11:19:17 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Feb 26, 2015 11:19:18 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Feb 26, 2015 11:19:18 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Feb 26, 2015 11:19:19 AM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.0.0.Final
Exception Thrown org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

`

`

最佳答案

在配置文件中添加多个映射文件的操作如下

 <mapping resource="path/Address.hbm.xml"/>
 <mapping resource="path/Employee.hbm.xml"/>

关于mysql - 如何在hibernate的配置文件中拥有多个映射资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28735160/

相关文章:

mysql - 通过迁移向导将 QODBC 连接到 MySQL 时出错

java - 像oracle中的搜索一样吗?

php - 检查用户登录时的多种条件

mysql 创建表数据目录不起作用

java - Hibernate:是否可以只保留一个 child ,这也会导致 parent 的坚持

java - 多个 Hibernate envers FirstLevelCache 实例

java - Spring data jpa存储库通过多元素查找

java - 在 Restful Web 服务中输入数据验证(是否使用空对象)

c# - 无法生成代码,类型为“System.Data.Design.InternalException”的异常

mysql - 数据库表设计