0

我是使用 Hibernate 的新手,但我需要将它用于工作项目。我们正在使用带有 Derby Embedded 的 Netbeans,我们无法更改为不同的 IDE。

我遇到的问题与数据库中的多对多关系有关。

我有一个表问题、一个表 MACHINE 和一个连接表 MACHINEPROBLEM。一个问题可以有很多机器,一台机器可以有很多问题。这些表通过联结表 MACHINEPROBLEM 关联。

我有必要的 POJO 和映射文件(在 hibernate.cfg.xml 中适当地引用)并让 Netbeans 和 Hibernate 自动在数据库中创建表。表和相应的关系已正确创建。表 MACHINEPROBLEM 有一个复合键,它由引用 MACHINE 表中的“id”的“machineid”和引用 PROBLEM 表中的“id”的“problemid”组成。

发生的事情是,当我创建一个问题对象时,向它添加一组机器,然后将其保存在数据库中,联结表没有被任何数据填充。数据正确保存在 PROBLEM 和 MACHINE 表中,但 MACHINEPROBLEM 表为空。这意味着我无法搜索给定问题的所有机器,因为用于连接它们的联结表是空的。

谁能帮我解决这个问题?谢谢。


映射文件:

机器.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="DataAccess.entity.Machine" table="MACHINE" schema="APP">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <set name="problems" inverse="false" lazy="true" fetch="select" table="MACHINEPROBLEM">
         <key column="MACHINEID"/>
         <many-to-many column="PROBLEMID" class="DataAccess.entity.Problem"/>
        </set>
        <property name="machineid" type="string">
            <column name="MACHINEID" length="10" not-null="true" />
        </property>
    </class>
</hibernate-mapping>



问题.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="DataAccess.entity.Problem" table="PROBLEM" schema="APP">
        <id name="id" type="long">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <set name="machines" inverse="true" lazy="true" fetch="select" cascade="all" table="MACHINEPROBLEM">
         <key column="PROBLEMID"/>
         <many-to-many column="MACHINEID" class="DataAccess.entity.Machine"/>
        </set>
        <property name="problemid" type="string">
            <column name="PROBLEMID" length="10" not-null="true" />
        </property>
        <property name="problemname" type="string">
            <column name="PROBLEMNAME" length="50" not-null="true" />
        </property>
        <property name="tipoproblema" type="string">
            <column name="TIPOPROBLEMA" length="50" />
        </property>
        <property name="linear" type="boolean">
            <column name="LINEAR" not-null="true" />
        </property>
        <property name="numtarefas" type="int">
            <column name="NUMTAREFAS" not-null="true" />
        </property>
        <property name="nummaquinas" type="int">
            <column name="NUMMAQUINAS" not-null="true" />
        </property>
    </class>
</hibernate-mapping>



POJO:

机器.java

public class Machine  implements java.io.Serializable {


     private long id;
     private String machineid;
     private Set<Problem> problems = new HashSet<Problem>();

    public Machine() {
    }

    public Machine(long id, String machineid) {
       this.id = id;
       this.machineid = machineid;
    }

    public long getId() {
        return this.id;
    }

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

    public String getMachineid() {
        return this.machineid;
    }

    public void setMachineid(String machineid) {
        this.machineid = machineid;
    }

     public Set<Problem> getProblems() {
      return problems;
    }

    public void setProblems( Set<Problem> problems ) {
      this.problems = problems;
     }

    public boolean equals(Object obj) {
      if (obj == null) return false;
      if (!this.getClass().equals(obj.getClass())) return false;

      Machine obj2 = (Machine)obj;
      if((this.id == obj2.getId()) && (this.machineid.equals(obj2.getMachineid())))
      {
         return true;
      }
      return false;
    }

    public int hashCode() {
       int tmp = 0;
       tmp = ( id + machineid ).hashCode();
       return tmp;
    }
}



问题.java

public class Problem  implements java.io.Serializable {


     private long id;
     private String problemid;
     private String problemname;
     private String tipoproblema;
     private boolean linear;
     private int numtarefas;
     private int nummaquinas;
     private Set<Machine> machines = new HashSet<Machine>();

    public Problem() {
    }


    public Problem(long id, String problemid, String problemname, boolean linear, int numtarefas, int nummaquinas) {
        this.id = id;
        this.problemid = problemid;
        this.problemname = problemname;
        this.linear = linear;
        this.numtarefas = numtarefas;
        this.nummaquinas = nummaquinas;
    }

    public Problem(long id, String problemid, String problemname, String tipoproblema, boolean linear, int numtarefas, int nummaquinas) {
       this.id = id;
       this.problemid = problemid;
       this.problemname = problemname;
       this.tipoproblema = tipoproblema;
       this.linear = linear;
       this.numtarefas = numtarefas;
       this.nummaquinas = nummaquinas;
    }

    public long getId() {
        return this.id;
    }

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

    public String getProblemid() {
        return this.problemid;
    }

    public void setProblemid(String problemid) {
        this.problemid = problemid;
    }

    public String getProblemname() {
        return this.problemname;
    }

    public void setProblemname(String problemname) {
        this.problemname = problemname;
    }

    public String getTipoproblema() {
        return this.tipoproblema;
    }

    public void setTipoproblema(String tipoproblema) {
        this.tipoproblema = tipoproblema;
    }

    public boolean isLinear() {
        return this.linear;
    }

    public void setLinear(boolean linear) {
        this.linear = linear;
    }

    public int getNumtarefas() {
        return this.numtarefas;
    }

    public void setNumtarefas(int numtarefas) {
        this.numtarefas = numtarefas;
    }

    public int getNummaquinas() {
        return this.nummaquinas;
    }

    public void setNummaquinas(int nummaquinas) {
        this.nummaquinas = nummaquinas;
    }

    public Set<Machine> getMachines() {
      return machines;
    }

    public void setMachines( Set<Machine> machines ) {
      this.machines = machines;
     }
}



主类:

public class Test {

    public static void main(String[] args) {    

        try
        {
             //Adds a couple of machines to a hashset
             Set<Machine> machines = new HashSet<>();
             machines.add(new Machine(1, "M1"));
             machines.add(new Machine(2, "M2"));

             //creates a Problem with some random data
             Problem p = new Problem(2, "OSD1", "TestP", "jobshop", true, 2, 3);    
             p.setMachines(machines);

             //Adds Problem p to the database
             ProblemDAL pDal = new ProblemDAL(null); 
             pDal.add(p); //Doing this saves Problem p to table PROBLEM, as well as the set of machines to table MACHINE. However, nothing's saved in the junction table MACHINEPROBLEM.

             pDal.closeSession();
        }
        catch (Exception e){
            e.printStackTrace();
        }

    }
}



问题DAL

public class ProblemDAL {
    Session session;
    boolean closeSession;

    public ProblemDAL(Session session)
    {
        if(session == null)
        {
            this.session = HibernateUtil.getSessionFactory().openSession();
        }
        else
        {
            this.session = session;
        }        
    }

    public void add(Problem entity) throws Exception {
        Transaction tx = null;

        try {
            tx = session.beginTransaction();
            session.save(entity);
            tx.commit();
        } 
        catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace(); 
        } 
    }

    public void update(Problem entity)
    {
        Transaction tx = null;

        try {            
            tx = session.beginTransaction();
            session.update(entity);
            tx.commit();
        }
        catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace(); 
        } 
    }

    public void delete(Problem entity){
        Transaction tx = null;

        try{
           tx = session.beginTransaction();         
           session.delete(entity); 
           tx.commit();
        }
        catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }
    }



    public Problem getById(long id) {
        Transaction tx = null;
        Problem entity = null;

        try {
            tx = session.beginTransaction();
            entity = (Problem) session.get(Problem.class, id);
            tx.commit();   
        }
        catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace(); 
        }
        finally {
            return entity;
        }

    }



    public List<Problem> getAll() {
        Transaction tx = null;
        List<Problem> entityList = null;

        try {
            tx = session.beginTransaction();
            entityList = session.createQuery("from Problem").list();
            tx.commit();             
        }
        catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace(); 
        }
        finally {
            return entityList;
        }
    }

    public List<Machine> getMachines() {
        Transaction tx = null;
        List<Machine> entityList = null;

        try {
            tx = session.beginTransaction();
            entityList = session.createQuery("select machines from Problem").list();
            tx.commit();             
        }
        catch (HibernateException e) {
            if (tx!=null) tx.rollback();
            e.printStackTrace(); 
        }
        finally {
            return entityList;
        }
    }

    public void closeSession()
    {
        if(this.session!=null)
        {
            this.session.close();
        }
    } 
}



休眠.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.connection.url">jdbc:derby:DB;create=true</property>
    <property name="hibernate.connection.username">***</property>
    <property name="hibernate.connection.password">***</property>
    <property name="hibernate.show_sql">true</property>
    <mapping resource="DataAccess/entity/Problem.hbm.xml"/>
    <mapping resource="DataAccess/entity/Machine.hbm.xml"/>
    <mapping resource="DataAccess/entity/Operation.hbm.xml"/>
    <mapping resource="DataAccess/entity/EvaluationParameters.hbm.xml"/>
    <mapping resource="DataAccess/entity/Generatedjobs.hbm.xml"/>
    <mapping resource="DataAccess/entity/Jobs.hbm.xml"/>
  </session-factory>
</hibernate-configuration>
4

1 回答 1

1

此类问题最常见的问题是您没有设置关系的双方。

目前忽略任何 Hibernate 问题,无论如何这是最好的做法。

如果你考虑:

Problem p = new Problem();
Machine m = new Machine();
m.addProblem(p);

忽略任何持久性问题,您的域模型是否处于一致状态,即。机器“m”是否与问题“p”相关联?即 p.getMachines().contains(m) 是否返回 true?

所以通常最好封装这些操作:

public class Machine{

public void addProblem(Problem p){
problems.add(p);
p.getMachines.add(this);
}


public class Problem{
public void addMachine(Machine m){
machines.add(m);
m.getProblems().add(this);
}

作为一个实验,您可以尝试使用当前代码来保存具有一组问题的新机器。结果应该与预期一样,因为机器是拥有(非反向)方。

于 2013-11-08T09:31:08.727 回答