0

帮我解决我的问题。当我使用方法getDriversByBus(Bus bus)时,我遇到了映射问题。

型号: Bus bus_id pk 号

驱动程序 driver_id pk 名称

busdriver bus_id fk driver_id fk

公共汽车

public class Bus {
    private Long id;
    private String number;
    private Set drivers = new HashSet();

    public Bus(){

    }

    public Long getId() {
        return id;
    }

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

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public Set getDrivers() {
        return drivers;
    }

    public void setDrivers(Set drivers) {
        this.drivers = drivers;
    }



}

司机

public class Driver {
    private Long id;
    private String name;
    private Set busses = new HashSet();

    public Driver(){

    }

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set getBusses() {
        return busses;
    }

    public void setBusses(Set busses) {
        this.busses = busses;
    }


}

1 级 - 司机:

public class DriverDAOImpl implements DriverDAO{

@Override
public void addDriver(Driver driver) throws SQLException {
    // TODO Auto-generated method stub
    Session session = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.save(driver);
        session.getTransaction().commit();


    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка при вставке", JOptionPane.OK_OPTION);
    }

}

@Override
public Collection getAllDrivers() throws SQLException {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Collection getDriversByBus(Bus bus) throws SQLException {
    // TODO Auto-generated method stub
    Session session = null;
    List drivers = new ArrayList<Driver>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Long bus_id = bus.getId();

        Query query = session.createQuery("select d"+
                " from com.ee.model.Driver d JOIN d.busses bus"
                + " where bus.id =:busid ").setLong("busid", bus_id);




        drivers = (List<Driver>)query.list();
        session.getTransaction().commit();



    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

    finally{
        if(session!=null && session.isOpen()){
            session.close();
        }
    }
    return drivers;
}
}

2 类 - 总线公共类 BusDAOImpl 实现 BusDAO {

@Override
public void addBus(Bus bus) throws SQLException {
    // TODO Auto-generated method stub

      Session session = null;
        try {
          session = HibernateUtil.getSessionFactory().openSession();
          session.beginTransaction();
          session.save(bus);
          session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
          JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка при вставке", JOptionPane.OK_OPTION);
        } finally {
          if (session != null && session.isOpen()) {

            session.close();
          }
        }
      }


@Override
public Collection getAllBusses() throws SQLException {
    // TODO Auto-generated method stub
       Session session = null;
        List busses = new ArrayList<Bus>();
        try {
          session = HibernateUtil.getSessionFactory().openSession();
          busses = session.createCriteria(Bus.class).list();
        } catch (Exception e) {
            e.printStackTrace();
          JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка 'getAll'", JOptionPane.OK_OPTION);
        } finally {
          if (session != null && session.isOpen()) {
            session.close();
          }
        }
        return busses;
      }


@Override
public Collection getDriverByBus(Driver driver) throws SQLException {
    // TODO Auto-generated method stub
    Session session = null;
    List busses = new ArrayList<Bus>();
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Long driver_id = driver.getId();
        Query query = session.createQuery("select b "+ 
        "from Bus b INNER JOIN b.drivers driver"+
                " where driver.id =:driverid ").setLong("driverid", driver_id);
        busses = (List<Bus>)query.list();
        session.getTransaction().commit();



    } catch (Exception e) {
        // TODO: handle exception
    }
    finally{
        if(session!=null && session.isOpen()){
            session.close();
        }
    }

    return busses;
}

}

我的映射:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 22.02.2013 19:34:10 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.ee.model.Bus" table="busses">
        <id name="id" type="java.lang.Long">
            <column name="bus_id" />
            <generator class="increment" />
        </id>
        <property name="number" type="java.lang.String">
            <column name="NUMBER" />
        </property>
        <set name="drivers" table="busdriver" inverse="false" lazy="false">
            <key>
                <column name="bus_id" />
            </key>
            <many-to-many column="driver_id" class="com.ee.model.Driver"></many-to-many>
        </set>
    </class>
</hibernate-mapping>


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 22.02.2013 19:34:20 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.ee.model.Driver" table="drivers">
        <id name="id" type="java.lang.Long">
            <column name="driver_id" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <set name="busses" table="busdriver" inverse="false" lazy="false">
            <key>
                <column name="driver_id" />
            </key>
            <many-to-many column="bus_id" class="com.ee.model.Bus"></many-to-many>

        </set>
    </class>
</hibernate-mapping>

主类:

public class EEMain {

    /**
     * @param args
     */
public static void main(String[] args) throws SQLException{
    // TODO Auto-generated method stub



    Collection busses = Factory.getInstance().getBusDAO().getAllBusses();
    Iterator iter = busses.iterator();
    System.out.println("All busses");
    while(iter.hasNext()){
        Bus bus = (Bus) iter.next();
        Collection drivers = Factory.getInstance().getDriverDAO().getDriversByBus(bus);
        Iterator itr2 = drivers.iterator();
        System.out.println("Bus # " + bus.getNumber());
        while (itr2.hasNext()){
            Driver driver =  (Driver) itr2.next();
            System.out.println("Name: "+ driver.getName());
        }
    }



}

}

休眠.cfg

 <?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 name="ee">
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://127.0.0.1/mydb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.pool_size">1</property>
    <property name="current_session_context_class">thread</property>
    <property name="show_sql">true</property>
    <mapping resource="com/ee/model/Driver.hbm.xml"/>
    <mapping resource="com/ee/model/Bus.hbm.xml"/>
    </session-factory>
     </hibernate-configuration>

工厂

public class Factory {
    private static BusDAO busDAO = null;
    private static DriverDAO driverDAO = null;
    private static Factory instance = null;

     public static synchronized Factory getInstance(){
            if (instance == null){
              instance = new Factory();
            }
            return instance;
          }


      public BusDAO getBusDAO(){
        if (busDAO == null){
          busDAO = new BusDAOImpl();
        }
        return busDAO;
      }

      public DriverDAO getDriverDAO(){
        if (driverDAO == null){
          driverDAO = new DriverDAOImpl();
        }
        return driverDAO;
      }

}

休眠实用程序:

public class HibernateUtil {
      private static final SessionFactory sessionFactory;
        static {
          try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
          } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
          }
        }

        public static SessionFactory getSessionFactory() {
          return sessionFactory;
        }
    }

错误文字:

log4j:WARN 找不到记录器 (org.jboss.logging) 的附加程序。
log4j:WARN 请正确初始化 log4j 系统。
休眠:从总线 this_ 中选择 this_.bus_id 作为 bus1_2_0_,this_.NUMBER 作为 NUMBER2_0_
休眠:选择drivers0_.bus_id作为bus2_2_1_,drivers0_.driver_id作为driver1_1_1_,driver1_.driver_id作为driver1_0_0_,driver1_.NAME作为NAME0_0_从busdriver drivers0_内部连接drivers driver1_ on drivers0_.driver_id=driver1_.driver_id where drivers0_.bus_id=?
休眠:选择busses0_.driver_id作为driver1_0_1_,busses0_.bus_id作为bus2_1_1_,bus1_.bus_id作为bus1_2_0_,bus1_.NUMBER作为NUMBER2_0_从busdriver busses0_内部连接busses bus1_ on busses0_.bus_id=bus1_.bus_id where busses0_.driver_id=?
所有巴士
org.hibernate.hql.internal.ast.QuerySyntaxException:驱动程序未映射[从驱动程序 d 中选择 d,总线 b 其中 d.id = b.id 和 b.id =:busid]
10 号巴士
    在 org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
    在 org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
    在 org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
    在 org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
    在 org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3291)
    在 org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3180)
    在 org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
    在 org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
    在 org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    在 org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    在 org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
    在 org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
    在 org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    在 org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:105)
    在 org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:80)
    在 org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    在 org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    在 org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    在 org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1735)
    在 com.ee.DAO.DriverDAOImpl.getDriversByBus(DriverDAOImpl.java:59)
    在 com.ee.EEMain.main(EEMain.java:36)

4

2 回答 2

0

在我看来,mode.Driver 和 model.Driver 之间存在混淆。从 Hibernate 生成的 SQL 和错误消息都在谈论 com.ee.mode.Driver 但上面的大多数映射和代码都有 com.ee.model.Driver。

我在上面的代码中看不到错误,如果它在 java 中,它可能无法编译,因此我怀疑配置正在获取一个比上面问题中的映射文件更旧的映射文件,该文件已被更正。

我认为真正的问题是 Hibernate 正在 Bus 类中寻找一个名为“drivers”的集合。我认为 Bus 类的代码没有包含在上面,但我认为这是问题的核心。也许它有错误的名称或其他东西。它应该看起来像:

public class Bus {
private int id;
// Blah blah
private Set drivers;
// blah 
}
于 2013-02-23T13:18:17.960 回答
0

让我们尝试隔离问题源。由于您将您的集合声明为非懒惰。当您尝试迭代 bus.getDrivers() Set 时,它会告诉您什么?

于 2013-02-23T13:55:41.217 回答