Haofang Liu
Haofang Liu

Reputation: 141

how to create object with @GeneratedValue(strategy = GenerationType.AUTO)

I'm new to java EE and now I have some questions about creating a new object of entity Transactiontype. TransactionType entity class As you can see that I have created a one to many relationship (one transactiontype can have zero or many payments), I have assigned two attributes for transactionType: id(autogeneration) and transactionType(String). There is also a set of payments and I want to know: 1. I just to add id and transactionType in transactionType table, how can I create an object without adding any payments to it? 2. How should I pass the auto generated value-->id when I created the object here?

Sorry for these stupid questions I really cannot figure it out.

Upvotes: 1

Views: 697

Answers (1)

RazvanParautiu
RazvanParautiu

Reputation: 2938

First of all using JPA you map a Java object to a row of SQL table and vice versa.

  1. When you add @GeneratedValue annotation on id parameter, under the hood the JPA will treat the id as a primary key SQL equivalence. So there is no need to set the id when you persist a Java object; the id will be automatically generated.
  2. When you set @OneToMany annotation the equivalence in SQL is one-to-many relationship. If you do not want to set payments just don't do it...

Some code to persist:

1.You must to inject EntityManager

@PersistenceContext(unitName = "myPU")
    private EntityManager entityManager;

2. Persist the POJObjcte (Java Transaction API (JTA) will handle it)

  @Transactional(value = TxType.REQUIRED)
  public TransactionType create(@NotNull TransactionType item) {
        item.setPayment(payments); //it is not mandatory if you do not want to have payments
        item = entityManager.persist(item);
        return item;
 }    

After you persist the item, the id will be set automatically .

Upvotes: 1

Related Questions