Getting null value in foreign Key in hibernate oneTomany bidirectional relation

Viewed 43

I am getting null value in foreign-key in one to many relation here is my code:

This is AccountType class

@Entity
public class AccountType {
    
    @Id
    @GeneratedValue
    private int id;
    
    private String type;
    
    private int accountNo;
    
    
    /* @JoinColumn(name="customerID") */
    @ManyToOne
    @JoinColumn(name="customerID")
    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public AccountType() {
        super();
        // TODO Auto-generated constructor stub
    }

    public AccountType(int id, String type, int accountNo) {
        super();
        this.id = id;
        this.type = type;
        this.accountNo = accountNo;
    }

//getters & setters

Class -> Customer.java (customer can have many account)

@Entity
public class Customer {
    
    @Id
    @GeneratedValue
    private int customerID;
    
    private String customerName;
    
    /* @OneToMany(cascade = {CascadeType.ALL}) */
    
    @OneToMany(mappedBy ="customer" )
    private List<AccountType> accountType;

    
    public Customer() {
        super();
    }
//getters & setters

Hibernate Config File: enter image description here

This is my Main Class

public static void main(String[] args) {
        
        SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.getCurrentSession();
        
        Customer customer = new Customer();
        customer.setCustomerName("Pooja kadu");
        
        AccountType accountTypeSaving = new AccountType();
        accountTypeSaving.setType("saving account");
        accountTypeSaving.setAccountNo(12345);
        
        AccountType accountTypeCurrent = new AccountType();
        accountTypeCurrent.setType("Current account");
        accountTypeCurrent.setAccountNo(1235);
        
        
        
        List<AccountType> list = new ArrayList<AccountType>(); 
        list.add(accountTypeSaving);
        list.add(accountTypeCurrent);
        
        customer.setAccountType(list);
        
        session.beginTransaction();
        
        session.save(accountTypeCurrent);
        session.save(accountTypeSaving);
        
        session.save(customer);
        
        
        session.getTransaction().commit();
        
//      System.out.println(list.get(0).getCustomer().getCustomerID());
        
    }

DataBase Value after exec: Account table information

Customer table values

0 Answers
Related