hql会话保存后,主键每次显示0

r1zk6ea1  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(333)

下面是我的代码,请帮助我找出为什么主键每次都是0,尽管记录被正确地插入数据库。我在google上查过解决方案,它说sessionsave方法应该返回正确的主键。

sessionFactory = HibernateUtil.sessionFactory;    
        session = sessionFactory.openSession();
        session.beginTransaction();         
        Long currentTime =System.currentTimeMillis();
        int primary_key_mailID;
        EmailInfo emailObj;

        for(int i=0;i<mailDtos.size();i++)
        {
            try
            {       

                mailDTO = mailDtos.get(i);
                emailObj = new EmailInfo();                 

                emailObj.setDomain_id(domainNameToIdMap.get(mailDTO.getToEmail().trim()));
                emailObj.setClient_id(clientEmailToIdMap.get(mailDTO.getFromEmail().trim()));
                emailObj.setMail_cc(mailDTO.getCc()!=null? Arrays.toString(mailDTO.getCc()):"");
                emailObj.setMail_bcc(mailDTO.getBcc()!=null? Arrays.toString(mailDTO.getBcc()):"");
                emailObj.setMail_subject(mailDTO.getSubject());
                emailObj.setMail_creation_time(currentTime);
                emailObj.setStatus("new");
                emailObj.setSource("mail");                 

                primary_key_mailID = (Integer) session.save(emailObj);      
                System.out.println(primary_key_mailID);             

            }
            catch (Exception e) {                   
                e.printStackTrace();
            } 
        }

        session.getTransaction().commit();
gorkyyrv

gorkyyrv1#

添加

@GeneratedValue(strategy = GenerationType.IDENTITY)

用主键列解决了问题。

相关问题