下面列出了怎么用org.hibernate.NonUniqueResultException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Room getRoomByRoomNumber(String roomNumber) {
try {
session = dataSourceFactory.getSessionFactory().openSession();
beginTransactionIfAllowed(session);
Query<Room> query = session.createQuery("from Room where number=:roomNumber", Room.class);
query.setParameter("roomNumber", roomNumber);
logging.setMessage("RoomDaoImpl -> fetching room by number "+roomNumber);
return query.getSingleResult();
} catch (NonUniqueResultException e) {
logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
final InformationFrame frame = new InformationFrame();
frame.setMessage("There is more than one room with this number!");
frame.setVisible(true);
}
session.close();
return null;
}
@Override
public Room getRoomByReservId(long id) {
try {
session = dataSourceFactory.getSessionFactory().openSession();
beginTransactionIfAllowed(session);
Query<Room> query = session.createQuery("from Room where ReservationId=:id", Room.class);
query.setParameter("id", id);
logging.setMessage("RoomDaoImpl -> fetching room by identity :"+id);
return query.getSingleResult();
} catch (NonUniqueResultException e) {
session.getTransaction().rollback();
logging.setMessage("RoomDaoImpl -> "+e.getLocalizedMessage());
final InformationFrame frame = new InformationFrame();
frame.setMessage(e.getLocalizedMessage());
frame.setVisible(true);
}
session.close();
return null;
}
public static DepartmentalInstructor findByPuidDepartmentId(String puid, Long deptId, org.hibernate.Session hibSession) {
try {
return (DepartmentalInstructor)hibSession.
createQuery("select d from DepartmentalInstructor d where d.externalUniqueId=:puid and d.department.uniqueId=:deptId").
setString("puid", puid).
setLong("deptId",deptId.longValue()).
setCacheable(true).
setFlushMode(FlushMode.MANUAL).
uniqueResult();
} catch (NonUniqueResultException e) {
Debug.warning("There are two or more instructors with puid "+puid+" for department "+deptId+" -- returning the first one.");
return (DepartmentalInstructor)hibSession.
createQuery("select d from DepartmentalInstructor d where d.externalUniqueId=:puid and d.department.uniqueId=:deptId").
setString("puid", puid).
setLong("deptId",deptId.longValue()).
setCacheable(true).
setFlushMode(FlushMode.MANUAL).
list().get(0);
}
}
public static <R> R uniqueElement(List<R> list) throws NonUniqueResultException {
int size = list.size();
if ( size == 0 ) {
return null;
}
R first = list.get( 0 );
for ( int i = 1; i < size; i++ ) {
if ( list.get( i ) != first ) {
throw new NonUniqueResultException( list.size() );
}
}
return first;
}
static Object uniqueElement(List list) throws NonUniqueResultException {
int size = list.size();
if (size==0) return null;
Object first = list.get(0);
for ( int i=1; i<size; i++ ) {
if ( list.get(i)!=first ) {
throw new NonUniqueResultException( list.size() );
}
}
return first;
}