表 :paperchoice   字段:paperId   choiceId  不是自增的 
                        1             2
                        1             3
                        1             8
                       20             25
                       20             28
现在如果插入 (1,2)的话就会报错 需求就是不允许插入重复数据 
 框架用的是struts2+hibernate···求大牛支招哇!!!

action:
public String addPaperChoice() {
if(paperchoices != null && paperchoices.size() > 0){
for(int i = 0; i < paperchoices.size(); i++){
int value_int, pid;
String value_str = paperchoices.get(i);
if(value_str != null && value_str != ""){
value_int = Integer.parseInt(value_str);
} else {
value_int = 0;
}
if(paperId != null && paperId != ""){
pid = Integer.parseInt(paperId);
} else {
pid = 0;
}
if(value_int != 0 && pid != 0){
PaperChoice pc = new PaperChoice();
pc.setChoiceId(value_int);
pc.setPaperId(pid);
paperService.addPaperChoice(pc);
}
}
return "success";
}
        // 容错处理...

return "input"; 
}dao层
public boolean addPaperChoice(PaperChoice paperchoice) {
Long i=null; Session session = HibernateSessionFactory.getSession();
Transaction tx = null;
try
{
tx = session.beginTransaction();
session.save(paperchoice);

tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
if(tx!=null){
tx.rollback();
}
throw e;
}finally{
HibernateSessionFactory.closeSession();
} return true;
}在这基础上 怎么改?

解决方案 »

  1.   

    paperId choiceId 能不能把这两个设置为主键
      

  2.   

    在你获取到paperId choiceId 这两个值后,先count下,如果结果大于零,则提示不允许插入,否则就执行添加操作。建议用存储过程实现。
      

  3.   


    那么捕捉到异常后,判断下是否主键冲突的异常。
    如果是,则不要继续抛出异常了,而是返回提示信息就好了,比如 return "duplicate";
    然后记得给duplicate配置对应页面负责提示主键重复。
      

  4.   

    先用paperId与choiceId一起作为条件去查数据库中是否已经存在,如果存在则提示重复;如果不存在则插入
      

  5.   

    catch到异常以后return到你想要的页面不就行了
      

  6.   

    这很简单啊,就是13楼回复的,不懂写?我帮你写一个:paperId choiceId
    1          2
    1          3
    1          8
    20         25
    20         28在hibernate里面,写这样一个方法,这个方法的作用是判断数据库是否存在那条记录,如果存在则返回true, 否则返加false,传入两个参数:
    public Boolean isExistPaperchoice(paperId, choiceId) {
    Session session = HibernateSessionFactory.getSession();
    session.beginTransaction();
    Query q = session.createQuery(
    "select count(*) from paperchoice where paperId = :x and choiceId = :y") ;
            q.setParameter("x", paperId);
    q.setParameter("y", choiceId);
            long count = (Long)q.uniqueResult();
    session.getTransaction().commit();
            if(count == 0)
                return false;
            return true;
    }然后再你的程序里面加上这一段:
    if(isExistPaperchoice(paperId, choiceId) == false) {
        addPaperChoice(PaperChoice paperchoice)
    }