我正在创建宠物诊所。如果用户想要添加新宠物,则必须输入所有者ID。如何检查此Id是否已存在。如果不是我想使用重定向到新表单,用户可以在其中添加新的所有者。
<tr>
<td><label>Owner: </label></td>
<td><form:input path="ownerId"/></td>
</tr>
编辑: 我想检查数据库中是否存在。我在MySQL中有两个表。所有者和宠物。所有者可以拥有许多宠物,宠物只能拥有一个所有者。
Part of Pet Class:
@Entity
@Table(name="pet")
public class Pet {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="type")
private String type;
@Column(name="name")
private String name;
@Column(name="sickness")
private String sickness;
@Column(name="owner_id")
private String ownerId;
...
}
所有者类:
@Entity
@Repository
public class Owner {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="phone_number")
private String phoneNumber;
...
}
控制器
@Controller
@RequestMapping("/pet")
public class PetController {
@Autowired
private PetService petService;
@GetMapping("/list")
public String listPets(Model theModel){
List<Pet> thePets = petService.getPets();
theModel.addAttribute("pets", thePets);
return "list-pets";
}
...
@PostMapping("/savePet")
public String savePet(@ModelAttribute("pet") Pet thePet){
petService.savePet(thePet);
return "redirect:/pet/list";
}
}
Serive
@Service
public class PetServiceImpl implements PetService{
@Autowired
private PetDAO petDAO;
@Transactional
public List<Pet> getPets() {
return petDAO.getPets();
}
@Transactional
@Override
public void savePet(Pet thePet) {
petDAO.savePet(thePet);
}
}
DAO
@Repository
public class PetDAOImpl implements PetDAO {
@Autowired
private SessionFactory sessionFactory;
public List<Pet> getPets() {
Session currentSession = sessionFactory.getCurrentSession();
Query<Pet> theQuery = currentSession.createQuery("from Pet", Pet.class);
List<Pet> thePets = theQuery.getResultList();
return thePets;
}
@Override
public void savePet(Pet thePet) {
Session currentSession = sessionFactory.getCurrentSession();
currentSession.saveOrUpdate(thePet);
}
}
答案 0 :(得分:0)
在JSP中,您可以使用JSTL核心库检查对象是否具有值:
<c:if test="${not empty pet.ownerId}">...</c:if>
其中pet是你的模型对象(传递给表单)。