IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Développement Web en Java Discussion :

HIbernate OneToMany / ManyToOne CRUD Object


Sujet :

Développement Web en Java

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut HIbernate OneToMany / ManyToOne CRUD Object
    Bonjour,

    Je souhaite créer une petite application permettant de faire un CRUD (Create/Read/Update/Delete) sur un objet (User)

    Donc j'ai une relation OneToMany et ManyToOne entre deux entités


    ########## USERS

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @Entity
    @Table(name = "users")
    public class Users implements Serializable {
     
        @Id
        @Column(name = "username")
        private String username;
        @Column(name = "password")
        private String password;
        @Column(name = "enabled")
        private Boolean enabled;
        @Column(name = "email")
        private String email;
     
        @OneToMany(cascade = CascadeType.ALL)
        private List<Authorities> authoritiesList;
    ########## AUTHORITIES

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Entity
    @Table(name = "authorities")
    public class Authorities implements Serializable {
     
        @EmbeddedId
        protected AuthoritiesPK authoritiesPK;
     
        @ManyToOne
        @JoinColumn(name = "username", insertable = false, updatable = false) 
        private Users users;
    ########## DAO

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
     
    public Users addUser(Users pUser, List<String> pListAuthorities) {
            EntityTransaction tx = getEM().getTransaction();
            tx.begin();
            getEM().persist(pUser);
     
            for (String authoritie : pListAuthorities) {
                AuthoritiesPK authoritiesPK = new AuthoritiesPK(pUser.getUsername(), authoritie);
                Authorities authorities = new Authorities(authoritiesPK);
                authorities.setUsers(pUser);
                getEM().persist(authorities);
            }
     
            tx.commit();
            return pUser;
        }
     
     
    public Users modifyUser(Users pUser) {
            EntityTransaction tx = getEM().getTransaction();
            tx.begin();
            pUser = getEM().merge(pUser);
            tx.commit();
            return pUser;
        }
     
    public void deleteUser(Users pUser) {
            EntityTransaction tx = getEM().getTransaction();
     
            if (pUser.getAuthoritiesList() != null) {
                tx.begin();
                List<Authorities> authoritieses = pUser.getAuthoritiesList();
                for (Authorities a : authoritieses) {
                    a.setUsers(null);
                }
                pUser.getAuthoritiesList().clear();
                pUser = getEM().merge(pUser);
                tx.commit();
            }
     
            tx.begin();
            getEM().remove(pUser);
            tx.commit();
        }
     
     
    protected EntityManager getEM() {
            if (em == null) {
                em = Persistence.createEntityManagerFactory(
                        JPA_UNIT_NAME).createEntityManager();
            }
            return em;
        }
    ##########Utilisation de PRIMEFACES

    Je possède un convertisseur sur ma liste

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    @FacesConverter("authoritiesConverter")
    public class AuthoritiesConverter implements Converter {
     
        private static final List<Authorities> LIST_AUTHORITIES;
     
        static {
            ArrayList<Authorities> tmp = new ArrayList<Authorities>();
            tmp.add(new Authorities("", "admin"));
            tmp.add(new Authorities("", "extended"));
            tmp.add(new Authorities("", "visitor"));
            LIST_AUTHORITIES = Collections.unmodifiableList(tmp);
        }
     
        @Override
        public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
            for (Authorities authorities : LIST_AUTHORITIES) {
                if (authorities.getAuthoritiesPK().getAuthority().equals(string)) {
                    return authorities;
                }
            }
            return null;
        }
     
        @Override
        public String getAsString(FacesContext fc, UIComponent uic, Object o) {
            return ((Authorities) o).getAuthoritiesPK().getAuthority();
        }
    ########## DIALOG USERS EDIT

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    <p:dialog header="Edit User" widgetVar="userEditDialog" resizable="false" id="userEditDlg"  
                  showEffect="fade" hideEffect="explode" modal="true" appendTo="@(body)" styleClass="dlg">  
            <h:form id="editForm">
                <p:panelGrid id="userEditDisplay" columns="2" styleClass="dlgPanelGroup"> 
                    <h:panelGroup>
                        <p:panelGrid columns="2" styleClass="dlgPanelGrid">  
                            <p:outputLabel value="Username : " styleClass="dlgLabel"/>  
                            <p:outputLabel value="#{userController.selectedUser.username}" styleClass="dlgLabelView"/>  
                            <p:outputLabel value="Password : " style="font-weight:bold" styleClass="dlgLabel"/>  
                            <p:inputText value="#{userController.selectedUser.password}" required="true"/>  
                            <p:outputLabel value="Email :" styleClass="dlgLabel"/>  
                            <p:inputText value="#{userController.selectedUser.email}"/> 
                            <p:outputLabel value="Enabled : " styleClass="dlgLabel"/>
                            <p:selectBooleanCheckbox value="#{userController.selectedUser.enabled}"/>
                        </p:panelGrid>
                    </h:panelGroup>
                    <h:panelGroup>
                        <p:panelGrid columns="2" styleClass="dlgPanelGrid">  
                            <p:outputLabel value="Authorities : " styleClass="dlgLabel"/> 
                            <p:selectManyCheckbox value="#{userController.selectedUser.authoritiesList}" 
                                                  layout="pageDirection"
                                                  converter="authoritiesConverter">
                                <f:attribute name="collectionType" value="java.util.ArrayList" />
                                <f:selectItems value="#{userController.listAuthorities}"/>
                            </p:selectManyCheckbox>
                        </p:panelGrid>
                    </h:panelGroup>
                </p:panelGrid>  
                <div align="right">
                    <p:commandButton value="Cancel" type="button" onclick="userEditDialog.hide()"  
                                     style="margin-top:10px;" icon="ui-icon-close" styleClass="buttonCancel"/> 
                    <p:commandButton id="editBtn" value="Save" oncomplete="userEditDialog.hide()"  
                                     action="#{userController.save()}" styleClass="buttonSave" ajax="false" 
                                     style="margin-top:10px;" icon="ui-icon-disk" update=":usersForm:users"/> 
                </div>
            </h:form>
        </p:dialog>

    J’arrive à ajouter un objet, mais j’ai des problèmes lors de l’ajout ou de la modification d’un objet user

    TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: entity.Authorities.users -> entity.Users

    ServletException: could not initialize a collection: [entity.Users.authoritiesList#


    MERCI DE VOTRE AIDE 

  2. #2
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Aucune Piste ?

  3. #3
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    salut,
    dans Users il te manque:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    @OneToMany(mappedBy="users", cascade = CascadeType.ALL)
        private List<Authorities> authoritiesList;
    Eric

  4. #4
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Merci, cela fonctionne un peu mieux mais j'ai cette erreur lorsque je veux modifier un user :

    com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`quickpass-user`.`authorities`, CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE NO ACTION)

    et quand j'ajoute un utilisateur et que je le supprime, j'ai cette erreur :

    java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: entity.Authorities.users -> entity.Users

  5. #5
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    Salut, une question:
    tu veux modifier quoi et ou?
    peux-tu nous montrer les syntaxes qui causent probleme?

    Eric

  6. #6
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Je souhaite Modifier les autorities d'un user

    # Controller

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     public void save() {
            LOGGER.info("" + getSelectedUser().getAuthoritiesList().size());
            pUserDao.modifyUser(getSelectedUser());
            String growlMessage = "The user : " + getSelectedUser().getUsername() + " has been saved";
            LOGGER.info(growlMessage);
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_INFO, growlMessage, growlMessage));
        }

    # DAO

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
     public Users modifyUser(Users pUser) {   
            EntityTransaction tx = getEM().getTransaction();
            tx.begin();
            pUser = getEM().merge(pUser);
            tx.commit();
            return pUser;
        }

    Erreur :

    Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1389)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1317)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:81)
    ... 46 more
    Caused by: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
    at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
    ... 46 more
    Caused by: java.sql.BatchUpdateException: Cannot add or update a child row: a foreign key constraint fails (`quickpass-user`.`authorities`, CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE NO ACTION)
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2054)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1467)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
    ... 54 more
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`quickpass-user`.`authorities`, CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE NO ACTION)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

  7. #7
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    fais nous voir comment tu crees ton et Eric

  8. #8
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    # GetEm()

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    protected EntityManager getEM() {
            if (em == null) {
                em = Persistence.createEntityManagerFactory(
                        JPA_UNIT_NAME).createEntityManager();
            }
            return em;
        }
    # Controller

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     private Users selectedUser = new Users();
     
       public Users getSelectedUser() {
            return selectedUser;
        }

  9. #9
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    donc tu sauvegardes un User vide; car il te faut d´abord sauvegarder authorities avant de sauvegarder users.

    Eric

  10. #10
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Non puisque mes users sont représentés dans un datatable et je fais ça quand je selectionne un user :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     <p:column styleClass="colButton">
                        <p:commandButton oncomplete="userEditDialog.show()" 
                                         update=":editForm:userEditDisplay"
                                         icon="ui-icon-pencil" title="Edit" 
                                         styleClass="buttonDatatable" >
                            <f:setPropertyActionListener value="#{user}"
                                                         target="#{userController.selectedUser}"/>
                        </p:commandButton>
    </p:column>
    donc selectedUser n'est pas un utilisateur vide

  11. #11
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    peux-tu afficher le contenue des autorithies que tu veux sauvegarder,
    car il semble que leur clé soit inexistant.
    1- soit inexsitant
    2- pas persister dans la base de données

    eric

  12. #12
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Voici la liste des users et une édition d'users

    Nom : Sans titre.png
Affichages : 627
Taille : 24,2 Ko

    Tu ne peux voir qu'il ne récupère pas l'authorities de l'utilisateur (aucune case n'est coché)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <h:panelGroup>
                        <p:panelGrid columns="2" styleClass="dlgPanelGrid">  
                            <p:outputLabel value="Authorities : " styleClass="dlgLabel"/> 
                            <p:selectManyCheckbox value="#{userController.selectedUser.authoritiesList}" 
                                                  layout="pageDirection"
                                                  converter="authoritiesConverter">
                                <f:attribute name="collectionType" value="java.util.ArrayList" />
                                <f:selectItems value="#{userController.listAuthorities}"/>
                            </p:selectManyCheckbox>
                        </p:panelGrid>
                    </h:panelGroup>
    Il récupère bien l'authorities :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    public Users modifyUser(Users pUser) {
     
            for (Authorities a : pUser.getAuthoritiesList()) {
                LOGGER.info(a.toString());
            }
    2014-03-12 12:33:13,457 76395 [qtp1678247383-31] INFO dao.UserDao - visitor
    2014-03-12 12:33:13,479 76417 [qtp1678247383-31] WARN o.h.util.JDBCExceptionReporter - SQL Error: 1452, SQLState: 23000
    2014-03-12 12:33:13,480 76418 [qtp1678247383-31] ERROR o.h.util.JDBCExceptionReporter - Cannot add or update a child row: a foreign key constraint fails (`quickpass-user`.`authorities`, CONSTRAINT `fk_authorities_users` FOREIGN KEY (`username`) REFERENCES `users` (`username`) ON DELETE CASCADE ON UPDATE NO ACTION)

    l'authorities n'est pas persisté ?

  13. #13
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    peux-tu nous donner le contenu de ta classe ?
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    @EmbeddedId
        protected AuthoritiesPK authoritiesPK;
    car c´est la ou se trouve le probleme.
    La je vais analyser cela avec toi.
    Eric

  14. #14
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    @Embeddable
    public class AuthoritiesPK implements Serializable {
     
        private static final long serialVersionUID = 1L;
     
        @Column(name = "username")
        private String username;
        @Column(name = "authority")
        private String authority;
     
        /**
         * Constructor
         */
        public AuthoritiesPK() {
        }

  15. #15
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    si j´ai bien compris, la relation entre Users et Authorities est many-to-many?

  16. #16
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Oui

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @Entity
    @Table(name = "users")
    public class Users implements Serializable {
     
        @Id
        @Column(name = "username")
        private String username;
        @Column(name = "password")
        private String password;
        @Column(name = "enabled")
        private Boolean enabled;
        @Column(name = "email")
        private String email;
     
        @OneToMany(mappedBy = "users", cascade = CascadeType.ALL)
        private List<Authorities> authoritiesList;

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    @Entity
    @Table(name = "authorities")
    public class Authorities implements Serializable {
     
        @EmbeddedId
        protected AuthoritiesPK authoritiesPK;
     
        @ManyToOne
        @JoinColumn(name = "username", insertable = false, updatable = false) 
        private Users users;

  17. #17
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    salut voici ce que je te propose:
    1. classe USERS :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     
    @Entity
    @Table(name = "users")
    public class Users implements Serializable {
     
        @Id
        @Column(name = "username")
        private String username;
        @Column(name = "password")
        private String password;
        @Column(name = "enabled")
        private Boolean enabled;
        @Column(name = "email")
        private String email;
     
        @ManyToMany(mappedBy="users",cascade = CascadeType.ALL)
        private List<Authorities> authoritiesList;
    2. classe Authorities
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    @Entity
    @Table(name = "authorities")
    public class Authorities implements Serializable {
     
        @EmbeddedId
        protected AuthoritiesPK authoritiesPK;
     
        @ManyToMany
        @JoinTable(name="Authorities_Users", 
          joinColumns=@JoinColumn(name="AUTHORITIES_ID"),
          inverseJoinColumns=@JoinColumn(name="USERS_ID"))  
        private Users users;

    tu crees une Table
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    Create Table  Authorities_Users
    (
      AUTHORITIES_ID COLUMN_TYPE,
      USERS_ID COLUMN_TYPE,
      CONSTRAINT `Authorities_Users_Users` FOREIGN KEY (`USERS_ID`) REFERENCES `USERS` (`username`),
      CONSTRAINT `Authorities_Users_Authorities` FOREIGN KEY (`AUTHORITIES_ID`) REFERENCES `AUTHORITIES` (`AUTHORITIES_ID`)
    );
    //
    creer des Tests.
    cela t´evitera beaucoup de problemes.

    Eric

  18. #18
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Merci mais je ne peux pas changer mes tables car j'utilise spring security

  19. #19
    Membre chevronné Avatar de jeffray03
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Juillet 2008
    Messages
    1 501
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Allemagne

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Juillet 2008
    Messages : 1 501
    Points : 2 120
    Points
    2 120
    Par défaut
    as-tu mis les methodes et das tes entités?
    et aussi une chose:
    tu ne peux pas mettre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    @EmbeddedId
        protected AuthoritiesPK authoritiesPK;
     
        @ManyToMany
        @JoinTable(name="Authorities_Users", 
          joinColumns=@JoinColumn(name="AUTHORITIES_ID"),
          inverseJoinColumns=@JoinColumn(name="USERS_ID"))  
        private Users users;
    et
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
       @EmbeddedId
        protected AuthoritiesPK authoritiesPK;
    soit l´un ou l´autre.
    Eric

  20. #20
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Décembre 2009
    Messages
    81
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Décembre 2009
    Messages : 81
    Points : 29
    Points
    29
    Par défaut
    Je ne veux pas changer les tables, je veux garder ce schéma de BDD.

    Voici mes entités :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    @Embeddable
    public class AuthoritiesPK implements Serializable {
     
        private static final long serialVersionUID = 1L;
     
        @Column(name = "username")
        private String username;
        @Column(name = "authority")
        private String authority;
     
        /**
         * Constructor
         */
        public AuthoritiesPK() {
        }
     
        /**
         *
         * @param username username
         * @param authority authority
         */
        public AuthoritiesPK(String username, String authority) {
            this.username = username;
            this.authority = authority;
        }
     
        public String getUsername() {
            return username;
        }
     
        public void setUsername(String username) {
            this.username = username;
        }
     
        public String getAuthority() {
            return authority;
        }
     
        public void setAuthority(String authority) {
            this.authority = authority;
        }
     
        @Override
        public int hashCode() {
            int hash = 0;
            hash += username != null ? username.hashCode() : 0;
            hash += authority != null ? authority.hashCode() : 0;
            return hash;
        }
     
        @Override
        public boolean equals(Object object) {
            if (!(object instanceof AuthoritiesPK)) {
                return false;
            }
            AuthoritiesPK other = (AuthoritiesPK) object;
            if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username))) {
                return false;
            }
            if ((this.authority == null && other.authority != null) || (this.authority != null && !this.authority.equals(other.authority))) {
                return false;
            }
            return true;
        }
     
        @Override
        public String toString() {
            return "entity.AuthoritiesPK[ username=" + username + ", authority=" + authority + " ]";
        }
    }

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    @Entity
    @Table(name = "authorities")
    public class Authorities implements Serializable {
     
        /**
         * SERIAL UID
         */
        private static final long serialVersionUID = 1L;
     
        /**
         *
         */
        @EmbeddedId
        protected AuthoritiesPK authoritiesPK;
     
        /**
         * ManyToOne Users
         */
        @ManyToOne
        @JoinColumn(name = "username", insertable = false, updatable = false) 
        private Users users;
     
        /**
         * Constructor
         */
        public Authorities() {
        }
     
        /**
         *
         * @param pAuthoritiesPK authoritiesPK
         */
        public Authorities(AuthoritiesPK pAuthoritiesPK) {
            this.authoritiesPK = pAuthoritiesPK;
        }
     
        /**
         *
         * @param pUsername username
         * @param pAuthority authority
         */
        public Authorities(String pUsername, String pAuthority) {
            this.authoritiesPK = new AuthoritiesPK(pUsername, pAuthority);
        }
     
        public AuthoritiesPK getAuthoritiesPK() {
            return authoritiesPK;
        }
     
        public void setAuthoritiesPK(AuthoritiesPK pAuthoritiesPK) {
            this.authoritiesPK = pAuthoritiesPK;
        }
     
        public Users getUsers() {
            return users;
        }
     
        public void setUsers(Users pUsers) {
            this.users = pUsers;
        }
     
        @Override
        public int hashCode() {
            int hash = 0;
            hash += authoritiesPK != null ? authoritiesPK.hashCode() : 0;
            return hash;
        }
     
        @Override
        public String toString() {
            return authoritiesPK.getAuthority();
        }
     
        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Authorities other = (Authorities) obj;
            if (this.authoritiesPK != other.authoritiesPK && (this.authoritiesPK == null || !this.authoritiesPK.equals(other.authoritiesPK))) {
                return false;
            }
            return true;
        }
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
     
    @Entity
    @Table(name = "users")
    public class Users implements Serializable {
     
        /**
         * SERIAL UID
         */
        private static final long serialVersionUID = 1L;
     
        @Id
        @Column(name = "username")
        private String username;
        @Column(name = "password")
        private String password;
        @Column(name = "enabled")
        private Boolean enabled;
        @Column(name = "email")
        private String email;
     
        @OneToMany(mappedBy = "users", cascade = CascadeType.ALL)
        private List<Authorities> authoritiesList;
     
        /**
         * Constructor
         */
        public Users() {
        }
     
        /**
         *
         * @param pUsername username
         */
        public Users(String pUsername) {
            this.username = pUsername;
        }
     
        /**
         *
         * @param pUsername username
         * @param pPassword password
         */
        public Users(String pUsername, String pPassword) {
            this.username = pUsername;
            this.password = pPassword;
        }
     
        public String getUsername() {
            return username;
        }
     
        public void setUsername(String pUsername) {
            this.username = pUsername;
        }
     
        public String getPassword() {
            return password;
        }
     
        public void setPassword(String pPassword) {
            this.password = pPassword;
        }
     
        public Boolean getEnabled() {
            return enabled;
        }
     
        public void setEnabled(Boolean pEnabled) {
            this.enabled = pEnabled;
        }
     
        public String getEmail() {
            return email;
        }
     
        public void setEmail(String pEmail) {
            this.email = pEmail;
        }
     
        public List<Authorities> getAuthoritiesList() {
            return authoritiesList;
        }
     
        /**
         *
         * @param pAuthoritiesList
         */
        public void setAuthoritiesList(List<Authorities> pAuthoritiesList) {
            this.authoritiesList = pAuthoritiesList;
        }
     
        @Override
        public int hashCode() {
            int hash = 0;
            hash += username != null ? username.hashCode() : 0;
            return hash;
        }
     
        @Override
        public boolean equals(Object object) {
            if (!(object instanceof Users)) {
                return false;
            }
            Users other = (Users) object;
            if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username))) {
                return false;
            }
            return true;
        }
     
        @Override
        public String toString() {
            return "entity.Users[ username=" + username + " ]";
        }
    }

Discussions similaires

  1. Aide sur les annotations Hibernate - @OneToMany
    Par gargantua dans le forum Hibernate
    Réponses: 1
    Dernier message: 19/03/2011, 16h33
  2. OneToMany ManyToOne - Pere/fils - Suppression du Set
    Par RhumRom dans le forum Hibernate
    Réponses: 4
    Dernier message: 03/08/2010, 20h04
  3. Problème suppression @OneToMany< -> @ManyToOne
    Par Invité dans le forum Persistance des données
    Réponses: 0
    Dernier message: 30/06/2010, 23h18
  4. Réponses: 1
    Dernier message: 02/09/2009, 09h22

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo