Я использую JSF2.0 / primefaces, MySql, Glassfish3.1.
У меня есть три таблицы: человек, файл, domaineCompetence
человек (имя, ......, idDomaineCompetence)
файл (idFile, nameFile, ......, idPerson)
domaineCompetence (idDomaineCompetence .....)
Когда человек добавляется в базу данных одновременно, будет добавлена строка
в таблицу файлов.
Но после отправки возникает ошибка. На самом деле у меня есть две ошибки. Я не знаю, почему один из них (не оба одновременно) появляются после выполнения программы.
index.xhtml:
<h:form>
<p:panel header="Add User" style="width: 500px; font-size: 14px">
<h:panelGrid width="width: 300px;" columns="2">
<h:outputLabel style="font-size: 13px" value="Nom" /> <h:inputText value="#{AddPerson.nom}" />
<h:outputLabel value="Prenom"/> <h:inputText value="#{AddPerson.prenom}" />
<h:outputLabel value="Etat Civil"/>
<h:selectOneMenu id="etatcivil" value="#{AddPerson.etatCivil}">
<f:selectItem itemValue="Monsieur" itemLabel="M"/>
<f:selectItem itemValue="Madam" itemLabel="Mme"/>
<f:selectItem itemValue="Madmoiselle" itemLabel="Mlle"/>
</h:selectOneMenu>
<h:outputLabel value="Date de naissance "/>
<p:calendar value="#{AddPerson.dateNaissance}" id="popupButtonCal" showOn="button" />
<h:outputLabel value="email"/><h:inputText value="#{AddPerson.email}" />
<h:outputLabel value="numTelephone"/><h:inputText value="#{AddPerson.numTelephone}" />
<h:outputLabel value="mobile"/><h:inputText value="#{AddPerson.mobile}" />
<h:outputLabel value="fax"/><h:inputText value="#{AddPerson.fax}" />
<h:outputLabel value="profession"/><h:inputText value="#{AddPerson.profession}" />
<h:outputLabel value="adresse"/><h:inputText value="#{AddPerson.adresse}" />
<h:outputLabel value="code Postal"/><h:inputText value="#{AddPerson.codePostal}" />
<h:outputLabel value="Ville"/><h:inputText value="#{AddPerson.ville}" />
<h:outputLabel value="Pays"/><h:inputText value="#{AddPerson.pays}" />
<h:outputLabel value="Domaine de Competence"/>
<h:selectOneMenu value="#{AddPerson.domain}" id="domaine" >
<f:selectItem itemLabel="-- Select Domaine de Competence-- " itemValue="0"/>
<f:selectItems value="#{AddPerson.listDomaine}" />
</h:selectOneMenu>
<h:outputLabel value="login"/><h:inputText value="#{AddPerson.login}" />
<h:outputLabel value="password"/><h:inputText value="#{AddPerson.password}" />
<p:fileUpload fileUploadListener="#{AddPerson.fileUpload}" update="messages" sizeLimit="500000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<h:commandButton action="#{AddPerson.addUserDB}" value="Add User" />
</h:panelGrid>
</p:panel>
</h:form>
Bean AddPerson.java:
public class AddPerson implements Serializable{
EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();
private String nom;
private String prenom;
private Date dateNaissance;
private String lieuNaissance;
private String etatCivil;
private String email;
private int numTelephone;
private int mobile;
private int fax;
private String profession;
private String login;
private String password;
private String adresse;
private int codePostal;
private String ville;
private String pays;
private FileUploadEvent event;
private File file;
private static List<SelectItem> listDomaine;
private String domain;
//getters and setters
public void fileUpload(FileUploadEvent event) throws IOException {
String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
String name = fmt.format(new Date())+ event.getFile().getFileName().substring(event.getFile().getFileName().lastIndexOf('.'));
file = new File("C:/Users/Documents/NetBeansProjects/test/uploaded files/" + name);
InputStream is = event.getFile().getInputstream();
OutputStream out = new FileOutputStream(file);
byte buf[] = new byte[1024];
int len;
while ((len = is.read(buf)) > 0)
out.write(buf, 0, len);
is.close();
out.close();
}
public List<SelectItem> getListDomaine() {
FindDomaine fdom= new FindDomaine();
if (listDomaine == null) {
listDomaine = new ArrayList<SelectItem>();
for (String val : fdom.FindAllDomaine()) {
listDomaine.add(new SelectItem(val));
}
}
return listDomaine;
}
public void addUserDB() {
try {
EntityTransaction entr = em.getTransaction();
entr.begin();
Personne user = new Personne();
Fileuploaded fileup =new Fileuploaded();
Domainecompetence dom=new Domainecompetence();
user.setNom(nom);
user.setPrenom(prenom);
user.setCodepostal(codePostal);
user.setEmail(email);
user.setEtatCivil(etatCivil);
user.setFax(fax);
user.setLieuNaissance(lieuNaissance);
user.setDateNaissance(dateNaissance);
user.setMobile(mobile);
user.setAdresse(adresse);
user.setPays(pays);
user.setLogin(login);
user.setPassword(password);
user.setPassword(password);
fileup.setFileName(file.getName());
fileup.setFilePath(file.getPath());
fileup.setIdPersonne(user);//add the forign key to the table fileupload
user.setDomaine(dom);
System.out.println("+++++Test+++++"+this.nom);
System.out.println("++++++Test++++"+this.prenom);
System.out.println("++++++Test++++"+this.domain);
em.persist(user);
em.persist(fileup);
entr.commit();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Failed");
} finally {
em.close();
}
}
}
persistance.xml
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="testPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>DTO.Domainecompetence</class>
<class>DTO.Personne</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
</persistence>
Error1:
Infos: Initialisation de Mojarra 2.1.3 (FCS b02) pour le contexte «/test»
Infos: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
Infos: Monitoring jndi:/server/test/WEB-INF/faces-config.xml for modifications
Infos: WEB0671: Loading application [test] at [/test]
Infos: test a été déployé en 3 485 ms.
Infos: file datejava.text.SimpleDateFormat@5069d960
Infos: file name :20120308103902.gif
Infos: ++++++++++julie
Infos: ++++++++++julie
Infos: ++++++++++Securite informatique
Infos: Object: DTO.Personne[ idPersonne=null ] is not a known entity type.
Infos: Failed
Ошибка 2:
Infos: file datejava.text.SimpleDateFormat@5069d960
Infos: file name :20120308102712.gif
Infos: Base de donnee
Infos: ++++++++++julie
Infos: ++++++++++julie
Infos: ++++++++++Base de donnee
Infos: [EL Warning]: 2012-03-08 10:27:15.604--UnitOfWork(5810583)--java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: DTO.Domainecompetence[ domaine=null ].
Infos: java.lang.IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: DTO.Domainecompetence[ domaine=null ].
Infos: Failed
Infos: PWC2785: Cannot serialize session attribute AddPerson for session 1a185521c447acaa561b45f616d7
personne.java
@Entity
@Table(name = "personne", catalog = "test", schema = "", uniqueConstraints = {
@UniqueConstraint(columnNames = {"idPersonne"})})
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Personne.findAll", query = "SELECT p FROM Personne p"),
@NamedQuery(name = "Personne.findByIdPersonne", query = "SELECT p FROM Personne p WHERE p.idPersonne = :idPersonne"),
@NamedQuery(name = "Personne.findByNom", query = "SELECT p FROM Personne p WHERE p.nom = :nom"),
@JoinColumn(name = "domaine", referencedColumnName = "domaine")
@ManyToOne
private Domainecompetence domaine;
Обновление:
domaineCompetence.java
@Entity
@Table(name = "domainecompetence", catalog = "test", schema = "")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Domainecompetence.findAll", query = "SELECT d FROM Domainecompetence d"),
@NamedQuery(name = "Domainecompetence.findByDomaine", query = "SELECT d FROM Domainecompetence d WHERE d.domaine = :domaine")})
public class Domainecompetence implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 200)
@Column(name = "domaine", nullable = false, length = 200)
private String domaine;
@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "domaine") //and I have tried CascadType.ALL
private Collection<Personne> personneCollection;
//getters and setters
}