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

hibernate类未映射

黄伟
2023-03-14

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

型号:Bus Bus\U id pk号

驱动程序driver_idpk名称

巴士司机bus_idfkdriver_idfk

巴士

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



}

}

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个答案

谭京
2023-03-14

在我看来,这两种模式之间似乎存在混淆。驱动程序和型号。驾驶员Hibernate生成的SQL和错误消息都是关于com的。ee。模式但是上面的大多数映射和代码都有com。ee。模型驾驶员

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

我认为真正的问题是Hibernate正在总线类中寻找一个名为“drivers”的集。我认为上面没有包含Bus类的代码,但我认为这是问题的核心。也许它的名字错了什么的。它应该看起来像:

public class Bus {
private int id;
// Blah blah
private Set drivers;
// blah 
}
蒲坚
2023-03-14

让我们试着找出问题的根源。因为您正在将集合声明为非懒惰。当您尝试在总线上迭代时,它会告诉您什么。getDrivers()设置?

 类似资料:
  • 我有一个产品数据库。我已经创建了一个简单的Hibernate项目来从数据库中检索所有的产品。但是,我在编译代码时出现了以下异常: 令人惊讶的是,将prodcuts添加到数据库中可以正常工作。

  • 我在Kotlin-vertx项目中配置了Hibernate,我设法设置了所有内容,但当我运行HQL查询时,它会输出: 提前谢了。

  • 问题内容: 这是错误 我不明白为什么会引发此错误,应该对类进行映射,因为我将简要地向您展示。我有一个非常基本的配置,例如:http : //docs.jboss.org/hibernate/annotations/3.5/reference/en/html/ch01.html 我试图将映射定义添加到hibernate.cfg.xml中,并且还尝试以编程方式添加它。他们俩都没有工作。有人可以告诉我我

  • 我正在构建一个REST API, 和ActiveBid类 和我的泽西请求映射器,它具有获取数据的逻辑 有人能帮我吗?我不知道和卡桑德拉共事会这么难。

  • 问题内容: 我不知道在hibernate状态下是否有可能。 我可以使用Hibernate的getSession()获得一个Bean类型(尚未映射)的列表吗? 我正在尝试从查询中获取两个值。这些值来自差异表。我已经完成查询,但是当我尝试执行getSession时,它说未映射我的班级。我没有映射它,因为没有要映射的表。我创建了一个名为ObjetivoAdapter的类,其中包含两个字符串(需要在列表中

  • 问题内容: 我正在使用“hibernate注释”找到我的脚,并且遇到了一个问题,希望有人可以提供帮助。 我有2个实体,分别是Section和ScopeTopic。该部分具有List类成员,因此具有一对多关系。运行单元测试时,出现此异常: 使用@OneToMany或@ManyToMany定位未映射的类:com.xxx.domain.Section.scopeTopic [com.xxx.domain