在spring数据中使用hibernate存储对象列表

时间:2018-06-18 06:42:17

标签: java spring hibernate

我需要在spring数据中使用hibernate在db中存储一个对象列表。基本上我需要将列表存储在与数据库的单个交互中。

为此,我正在尝试如下:

//a part of my code:
if(vacationAirTravellerLegInfoList.size() != 0) {   
            customVacationAirTravellerLegInfoRepository.save(vacationAirTravellerLegInfoList);
}

对于上面这部分,'customVacationAirTravellerLegInfoRepository'是我试图实现的自定义存储库的对象:

@Repository
public interface CustomVacationAirTravellerLegInfoRepository extends VacationAirTravellerLegInfoRepository, CrudRepository<VacationAirTravellerLegInfo, Integer> {
    List<VacationAirTravellerLegInfo> save(List<VacationAirTravellerLegInfo> airTravellerLegInfoList);

}

将此'save(List)'方法实现为:

public class CustomVacationAirTravellerLegInfoRepositoryImpl implements CustomVacationAirTravellerLegInfoRepository {

    private static SessionFactory sessionFactory;

    @Override
    public List<VacationAirTravellerLegInfo> save(List<VacationAirTravellerLegInfo> airTravellerLegInfoList) {

        try {
            //FIXME: exception on getting configuration object
            //sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); 
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Failed to create sessionFactory object." + ex);
            throw new ExceptionInInitializerError(ex);
        }
        Session session = sessionFactory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            for (int i = 0; i < airTravellerLegInfoList.size(); i++) {
                VacationAirTravellerLegInfo vacationAirTravellerLegInfo = airTravellerLegInfoList.get(i);
                session.save(vacationAirTravellerLegInfo);
            }
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return airTravellerLegInfoList;
    }

    //other inherited methods from the inherited are not mentioned here..

}

当我尝试执行customVacationAirTravellerLegInfoRepository.save(vacationAirTravellerLegInfoList);时,它会给出例外情况,如下所示:

{
    "timestamp": 1529303873662,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "org.springframework.beans.NotReadablePropertyException",
    "message": "Invalid property 'id' of bean class [java.util.ArrayList]: Could not find field for property during fallback access!",
    "path": "/api/server/vacation/save"
}

任何人都建议或纠正我。

1 个答案:

答案 0 :(得分:0)

可能需要投射列表元素

VacationAirTravellerLegInfo vacationAirTravellerLegInfo =  (VacationAirTravellerLegInfo) airTravellerLegInfoList.get(i);