当前位置: 首页 > 知识库问答 >
问题:

如何在Hibernate配置文件中拥有多个映射资源?

仲孙翔飞
2023-03-14

我有两张POJO的员工和地址表,还有两张员工和地址表。我首先尝试在db中添加一个地址行,然后添加一个员工记录,引用前面添加的地址记录。只有当配置文件中有一个映射资源时,我才能添加地址记录。

我的主文件:'包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>

我的任务是在数据库中添加一个地址记录,然后使用带有地址引用的employee构造函数添加一个employee记录。当employee表的映射资源被注释掉时,我可以添加地址记录,但如果我尝试同时添加这两个记录,则会出现错误。无法获取构造函数错误。

StackTrace:`debug:

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

'

'

共有1个答案

萧和同
2023-03-14

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

 <mapping resource="path/Address.hbm.xml"/>
 <mapping resource="path/Employee.hbm.xml"/>
 类似资料:
  • 我想为DropWizard创建几个yaml文件。其中一个包含敏感信息,另一个包含非敏感信息。 你能给我指出任何文档或例子如何在DropWizard中拥有多个配置吗?

  • 这是我的employee.hbm.xml: 所以,您可以注意到,在我的类中,它没有“id”属性。但是,我在数据库中创建id列,让它成为自动生成的主键。在这种情况下,我不知道应该在将我的类映射到我的数据库。如果我忽略了它,会不会是后来的一些问题呢?

  • XML 映射配置文件 MyBatis 的 XML 配置文件包含了影响 MyBatis 行为甚深的设置和属性信息。 XML 文档 的高层级结构如下: configuration 配置 properties 属性 settings 设置 typeAliases 类型命名 typeHandlers 类型处理器 objectFactory 对象工厂 plugins 插件 environments 环境 e

  • Hibernate 的常用配置文件主要分为 2 种:核心配置文件(hibernate.cfg.xml)和映射文件(Xxx.hbm.xml),它们主要用于配置数据库连接、事务管理、Hibernate 本身的配置信息以及 Hibernate 映射文件信息。 上节《 hibernate.cfg.xml》中讲解了 Hibernate 核心配置文件,本节我们继续讲解 Hibernate 映射文件。 Hibe

  • 我正试图在OpenShift上配置Nginx容器。我的最终目标是覆盖Nginx配置文件。我知道使用配置映射是可能的。因为修改Nginx配置目录的任何失败都会使容器崩溃,所以暂时我的目标是在/opt/app-root/src目录中创建一个index.html文件。 我面临两个问题取决于配置 配置映射覆盖整个/opt/app-root/src目录 配置映射在索引文件中创建index.html目录 配置

  • 问题内容: 有人可以解释在xml映射文件中使用逆函数的方法吗,我正在阅读本教程,但无法理解在映射文件中的逆用法? 谢谢 问题答案: 逆仅决定关系中的哪个实体负责更新数据库以反映关联。 假设一对多的双向关联。代码A和B中有两个类,A包含一组B,B维护对A的引用。在数据库级别,只有一个外键要更新,B的表包含一个到主键的列的A。 在这种情况下,假设我们将inverse = true放在集合侧。这意味着仅