参数化对象属性 [英] parameterizing object properties

查看:93
本文介绍了参数化对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以让我看到一种有效的代码方法,可以根据从超链接发送给它的参数来改变spring mvc中的对象属性吗?



我正在修改spring petclinic示例应用程序,以便所有者详细信息页面可以显示特定所有者拥有的每种类型宠物的单独列表。目前,宠物列表是每个所有者的财产,可以通过jstl作为owner.pets访问。我想要的是我的jstl代码能够从jstl调用owner.cats,owner.dogs,owner.lizards等,并在网页的不同部分填充多个单独的列表,即使所有的猫,狗,并且蜥蜴被存储在相同的底层数据表中。



我该如何完成这项工作?



以下是JpaOwnerRepositoryImpl.java的相关方法:

  @ SuppressWarnings(unchecked)
public Collection< Owner> findByLastName(String lastName){
//使用'join fetch',因为一个查询应该加载所有者和宠物
//使用'left join fetch',因为它可能发生所有者没有宠物然而
Query query = this.em.createQuery(SELECT DISTINCT owner FROM所有者所有者左连接获取owner.pets WHERE owner.lastName LIKE:lastName);
query.setParameter(lastName,lastName +%);
返回query.getResultList();
}

@Override
public所有者findById(int id){
//使用'join fetch',因为一个查询应该加载所有者和宠物
//使用'left join fetch',因为它可能发生所有者没有宠物
Query query = this.em.createQuery(SELECT owner FROM所有者所有者左连接获取owner.pets WHERE所有者。 id =:id);
query.setParameter(id,id);
return(所有者)query.getSingleResult();



$ b

以下是Owner.java的相关方面:

  @OneToMany(cascade = CascadeType.ALL,mappedBy =owner)
private Set< Pet>宠物;

保护套< Pet> getPetsInternal(){
if(this.pets == null){this.pets = new HashSet< Pet>();}
return this.pets;
}

公开列表< Pet> getPets(){
List< Pet> sortedPets = new ArrayList< Pet>(getPetsInternal());
PropertyComparator.sort(sortedPets,new MutableSortDefinition(name,true,true));
返回Collections.unmodifiableList(sortedPets);



$ b

这是管理url模式的OwnerController.java的一部分/拥有者我希望我的jstl能够在页面的不同部分分别列出猫,狗,蜥蜴等等(不是在一个分组列表中,而是在几个单独的列表中)。

  @RequestMapping(value =/ owners,method = RequestMethod.GET)
public String processFindForm(@RequestParam(ownerID)字符串ownerId,Owner所有者,BindingResult结果,Map< String,Object>模型){
Collection< Owner> results = this.clinicService.findOwnerByLastName();
model.put(选择,结果);
int ownrId = Integer.parseInt(ownerId);
model.put(sel_owner,this.clinicService.findOwnerById(ownrId));
返回owners / ownersList;


解决方案

-verbose解决方案,你可以做这种半脏修复。



Owner.java



  @Transient 
私人设置< Pet> cats = new HashSet< Pet>();

[...]

  //在将数据返回给页​​面之前,从OwnerController调用此函数。 $($ pet $ get)$ {
public void parsePets(){
for(Pet pet:getPetsInternal()){
if(cat.equals(pet.getType()。getName())){
cats.add(pet);
}
}
}

public getCats(){
return cats;
}



ownerDetail.jsp



  [...] 
< h3>猫< / h3>
< c:forEach var =catitems =$ {owner.cats}>
< p>名称:< c:out value =$ {cat.name}/>< / p>
< / c:forEach>

< h3>所有宠物< / h3>
[...]



OwnerController.java



  / ** 
*显示所有者的自定义处理程序。
*
* @param ownerId所有者的ID显示
* @返回带有视图模型属性的ModelMap
* /
@RequestMapping( / owner / {ownerId})
public ModelAndView showOwner(@PathVariable(ownerId)int ownerId){
ModelAndView mav = new ModelAndView(owners / ownerDetails);
所有者所有者= this.clinicService.findOwnerById(ownerId);
owner.parsePets();
mav.addObject(owner);
return mav;
}


Can someone show me a code efficient way to have an object property in spring mvc change based on parameters sent to it from a hyperlink?

I am modifying the spring petclinic sample application so that an "owner" detail page can show separate lists of each type of "pet" that the specific "owner" owns. Currently, a list of "pets" is a property of each "owner" and is accessible in jstl as owner.pets. What I want is for my jstl code to be able to call owner.cats, owner.dogs, owner.lizards, etc from jstl, and to populate several separate lists in different parts of the web page, even though all the cats, dogs, and lizards are stored in the same underlying data table.

How do I accomplish this?

Here are the relevant methods of JpaOwnerRepositoryImpl.java:

@SuppressWarnings("unchecked")
public Collection<Owner> findByLastName(String lastName) {
    // using 'join fetch' because a single query should load both owners and pets
    // using 'left join fetch' because it might happen that an owner does not have pets yet
    Query query = this.em.createQuery("SELECT DISTINCT owner FROM Owner owner left join fetch owner.pets WHERE owner.lastName LIKE :lastName");
    query.setParameter("lastName", lastName + "%");
    return query.getResultList();
}

@Override
public Owner findById(int id) {
    // using 'join fetch' because a single query should load both owners and pets
    // using 'left join fetch' because it might happen that an owner does not have pets yet
    Query query = this.em.createQuery("SELECT owner FROM Owner owner left join fetch owner.pets WHERE owner.id =:id");
    query.setParameter("id", id);
    return (Owner) query.getSingleResult();
}

Here are relevant aspects of Owner.java:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private Set<Pet> pets;

protected Set<Pet> getPetsInternal() {
    if (this.pets == null) {this.pets = new HashSet<Pet>();}
    return this.pets;
}

public List<Pet> getPets() {
    List<Pet> sortedPets = new ArrayList<Pet>(getPetsInternal());
    PropertyComparator.sort(sortedPets, new MutableSortDefinition("name", true, true));
    return Collections.unmodifiableList(sortedPets);
}

Here is the part of OwnerController.java that manages the url pattern "/owners" from which I want my jstl to be able to separately list cats, dogs, lizards, etc in separate parts of the page (not in one grouped list, but in several separate lists.):

@RequestMapping(value = "/owners", method = RequestMethod.GET)
public String processFindForm(@RequestParam("ownerID") String ownerId, Owner owner, BindingResult result, Map<String, Object> model) {
    Collection<Owner> results = this.clinicService.findOwnerByLastName("");
    model.put("selections", results);
    int ownrId = Integer.parseInt(ownerId);
    model.put("sel_owner",this.clinicService.findOwnerById(ownrId));
    return "owners/ownersList";
}

解决方案

Since you asked for a non-verbose solution, you could just do this kind of semi-dirty fix.

Owner.java

@Transient
private Set<Pet> cats = new HashSet<Pet>();

[...]

// Call this from OwnerController before returning data to page.
public void parsePets() {
  for (Pet pet : getPetsInternal()) {
    if ("cat".equals(pet.getType().getName())) {
      cats.add(pet);
    }
  }
}

public getCats() {
  return cats;
}

ownerDetail.jsp

[...]
<h3>Cats</h3>
<c:forEach var="cat" items="${owner.cats}">
    <p>Name: <c:out value="${cat.name}" /></p>
</c:forEach>

<h3>All pets</h3>
[...]

OwnerController.java

/**
 * Custom handler for displaying an owner.
 *
 * @param ownerId the ID of the owner to display
 * @return a ModelMap with the model attributes for the view
 */
@RequestMapping("/owners/{ownerId}")
public ModelAndView showOwner(@PathVariable("ownerId") int ownerId) {
    ModelAndView mav = new ModelAndView("owners/ownerDetails");
    Owner owner = this.clinicService.findOwnerById(ownerId);
    owner.parsePets();
    mav.addObject(owner);
    return mav;
}

这篇关于参数化对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆