【发布时间】:2016-07-21 07:34:35
【问题描述】:
如何从外键(restaurant_id 和 channel_id)中获取内容?我的意思不是 FK 值,而是 restaurant_id 的餐厅名称和 channel_id 的频道名称。
表:
型号:
@Entity
@Table(name = "restaurant")
public class Restaurant {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "restaurant_id")
private List<Booking> bookings;
...
@Entity
@Table(name = "channel")
public class Channel {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "channel_id")
private List<Booking> bookings;
...
@Entity
@Table(name = "booking")
public class Booking {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "restaurant_id", unique = true)
private Long restaurant_id;
@Column(name = "channel_id", unique = true)
private Long channel_id;
...
@Override
public String toString() {
return "Booking [id=" + id + ", name=" + name + ", count=" + count + ", duration=" + duration + ", start="
+ start + ", phone=" + phone + ", comment=" + comment + ", updated=" + updated + ", created=" + created
+ ", active=" + active + ", restaurant_id=" + restaurant_id + ", channel_id=" + channel_id + "]";
}
...
DAO
@Repository
public class BookingDaoImpl implements BookingDao {
private static final Logger logger = LoggerFactory.getLogger(BookingDaoImpl.class);
@Resource(name = "localSessionFactoryBean")
private SessionFactory sessionFactory;
@Override
public List<Booking> getBookings() {
Session session = this.sessionFactory.getCurrentSession();
List<Booking> bookingList = session.createCriteria(Booking.class).list();
for (Booking booking : bookingList) {
logger.info("Booking List::" + booking);
}
return bookingList;
}
...
服务
@Service
public class BookingServiceImpl implements BookingService {
@Autowired
private BookingDao bookingDao;
@Override
@Transactional
public List<Booking> getBookings() {
return bookingDao.getBookings();
}
...
控制器
@Controller
public class MainController {
@Autowired
private BookingService bookingService;
@RequestMapping(value = "bookings", method = RequestMethod.GET)
public String bookings(Model model) {
List<Booking> bookingList = bookingService.getBookings();
model.addAttribute("bookings", bookingList);
return "bookings";
}
...
JSP
<c:forEach items="${bookings}" var="booking">
<tr>
<td>${booking}</td>
</tr>
</c:forEach>
toString() 结果:
【问题讨论】:
-
您希望从哪里获取信息? JSP?控制器还是在 SQL 查询中?
-
JSP。现在我得到 restaurant_id=1,channel_id=1,但我想得到餐厅名称,或地址和频道名称。使用 id 我不能做太多事情。
标签: java mysql hibernate jsp spring-mvc