hibernate类没有映射

时间:2013-02-23 12:54:55

标签: java hibernate

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

型号: 总线 bus_id pk 号码

驱动 driver_id pk 名称

布德里弗 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>

MainClass:

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());
        }
    }



}

}

hibernate.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;
      }

}

的HibernateUtil:

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 No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select this_.bus_id as bus1_2_0_, this_.NUMBER as NUMBER2_0_ from busses this_
Hibernate: select drivers0_.bus_id as bus2_2_1_, drivers0_.driver_id as driver1_1_1_, driver1_.driver_id as driver1_0_0_, driver1_.NAME as NAME0_0_ from busdriver drivers0_ inner join drivers driver1_ on drivers0_.driver_id=driver1_.driver_id where drivers0_.bus_id=?
Hibernate: select busses0_.driver_id as driver1_0_1_, busses0_.bus_id as bus2_1_1_, bus1_.bus_id as bus1_2_0_, bus1_.NUMBER as NUMBER2_0_ from busdriver busses0_ inner join busses bus1_ on busses0_.bus_id=bus1_.bus_id where busses0_.driver_id=?
All busses
org.hibernate.hql.internal.ast.QuerySyntaxException: drivers is not mapped [select d from drivers d , busses b where d.id = b.id and b.id =: busid]
Bus # 10
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
    at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3291)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3180)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:221)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:199)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1735)
    at com.ee.DAO.DriverDAOImpl.getDriversByBus(DriverDAOImpl.java:59)
    at com.ee.EEMain.main(EEMain.java:36)

2 个答案:

答案 0 :(得分:0)

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

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

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

public class Bus {
private int id;
// Blah blah
private Set drivers;
// blah 
}

答案 1 :(得分:0)

让我们尝试隔离问题来源。因为你宣布你的集合是非懒惰的。当你尝试迭代bus.getDrivers()时,它会告诉你什么?