5 Replies Latest reply on May 4, 2011 4:30 PM by maxandersen

    How to add constructors with ID in pojo generation?

    bcn

      I would like to have constructors with the primary key / the ID in the entity classes generated by the domain code exporter.

      Do I have to modify the template PojoConstructors.ftl? If yes, how?

      I wonder why such constructors are not added by default.

       

      Thanks,

      Ulrich

        • 1. How to add constructors with ID in pojo generation?
          maxandersen

          Only makes sense if your use assigned id's and in that case they should actually be generated.

          • 2. How to add constructors with ID in pojo generation?
            bcn

            What is an assigned id?

             

            Maybe I am going the wrong way, but I explain what I try to do: I persist an new entity which has a child entity (many-to-one relationship). The entity has a foreign key of the child, but the child is not updated and already exists. The entity class has a field of type child entity.

            So I want to set the foreign key easily by

            entity.setChild(new ChildEntity(childId))

            instead of

            ChildEntity c = new ChildEntity();

            c.setId(childId);

            entity.setChild(c);

             

            3 lines instead of 1!

            I don't need to set the other fields of the child entity as it is not persisted.

             

            Thanks

            • 3. How to add constructors with ID in pojo generation?
              maxandersen

              assigned id is when you do not have autogenerated keys.

               

              entity.setChild(new ChildEntity(childId)) is rather bad since why do you want to have an incomplete objectgraph?

               

              better approach is:

               

              entity.setChild(session.load(ChildEntity.class, childId));

               

              That will do the same thing and wont load the childentity unless you try to access methods on it avoiding incomplete objectgraph.

              • 4. How to add constructors with ID in pojo generation?
                bcn

                I see, thanks.

                By "session.load()" do you mean EntityManager.find()? Or of which class is your session object?

                 

                I don't have auto-generated IDs, but the constructor(id) is not generated. Anyway, if your approach is better, I'll use that.

                • 5. How to add constructors with ID in pojo generation?
                  maxandersen

                  yes,

                   

                  em.find(Your.class, id) will work too.