为了学习JPA / JSF,我正在使用Eclipse J2EE(JSF primefaces和JPA)创建一个CRUD Web应用程序。
从技术上讲,每件事情都运行良好(根本没有错误)但是在检查我的数据库时我注意到在我的表中添加一个新条目(抛出一个jsf页面)后,ID(从序列生成)是否定的值(-46,-45,-44 ......等)。
以下是我的代码的相关部分:
1.我的实体:
@Entity
@NamedQuery(name="Book.findAll", query="SELECT b FROM Book b")
@SequenceGenerator(name="ma_seq", sequenceName="book_seq")
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ma_seq")
@Id private long id;
private String auteur;
private String langue;
private String titre;
public Book() {
}
//...getters and setters
}
我的托管bean
@ManagedBean( name="mybean")
@ViewScoped
public class Mymbean extends MyDAO implements Serializable {
private static final long serialVersionUID = 1L;
public void valider_ajout() throws SecurityException, IllegalStateException, NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException{
nouv_livre=new Book();
RequestContext context = RequestContext.getCurrentInstance();
FacesMessage message = null;
boolean added = false;
//appel de la fonction d'ajout
nouv_livre.setAuteur(aut);
nouv_livre.setTitre(tit);
nouv_livre.setLangue(lang);
System.out.println(nouv_livre.getTitre());
register(nouv_livre);
}
//other fonctions...
}
3.my DAO:
public class MyDAO {
//Constructeur
public MyDAO(){
}
@PersistenceContext
private EntityManager em;
@Resource
private UserTransaction userTransaction;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
@Transactional
public void register(Book livre) throws NotSupportedException, SystemException, SecurityException, IllegalStateException, RollbackException, HeuristicMixedException, HeuristicRollbackException {
// Save employee
userTransaction.begin();
this.em.persist(livre);
userTransaction.commit();
}
//other fonctions
}
我的XML:
<h:outputLabel for="auteur" value="Auteur" />
<p:inputText id="auteur" value="#{mybean.aut}" required="true" label="auteur" />
<h:outputLabel for="langue" value="Langue" />
<p:inputText id="langue" value="#{mybean.lang}" required="true" label="langue" />
<f:facet name="footer">
<p:commandButton value="Ajouter" actionListener="#{mybean.valider_ajout}"
oncomplete="handleLoginRequest(xhr, status, args)" />
</f:facet>
</h:panelGrid>
</p:dialog>
</h:form>
<script type="text/javascript">
function handleLoginRequest(xhr, status, args) {
if(args.validationFailed || !args.added) {
PF('dlg2').jq.effect("shake", {times:5}, 100);
}
else {
PF('dlg2').hide();
$('#loginLink').fadeOut();
location.reload();
}
}
提前谢谢。
答案 0 :(得分:0)
将其添加到@SequenceGenerator 后,工作正常!!!
allocationSize = 1