Results 1 to 2 of 2

Thread: Issue with Child Entity Save Spring JPA

  1. #1
    Join Date
    Dec 2010
    Posts
    5

    Default Issue with Child Entity Save Spring JPA

    Hi,

    I'm using Entity, JPA Repository, Service Layer and Controller for each entity actions in Spring MVC. It's working fine for each individual entity.

    Now, I'm trying to add a child entity named City to parent entity Country. I'm facing the issue here.

    Code:
    @Entity
    @Table(name="country")
    public class Country implements Serializable {
    	private Long id;
    	...
    	private List<City> cities;
    	...
    	@Id
    	@GeneratedValue(strategy=GenerationType.AUTO)
    	public Long getId() {
    		return this.id;
    	}
    	...
    	@OneToMany(mappedBy="country",fetch=FetchType.LAZY)
    	public List<City> getCities() {
    		return this.cities;
    	}
    }
    
    public interface CountryRepository extends JpaRepository<Country, Long> {
    }
    
    @Service("countryService")
    @Transactional(readOnly = true)
    public class CountryServiceImpl implements CountryService {
    	@Autowired
    	private CountryRepository repository;
    	...
    	@Transactional
    	public Country save(Country entity) {
    		return repository.save(entity);
    	}
    	...
    }
    
    @Entity
    @Table(name="city")
    public class City implements Serializable {
    	private Long id;
    	...
    	private Long countryID;
    	private Country country;
    	...
    	@Id
    	@GeneratedValue(strategy=GenerationType.AUTO)
    	public Long getId() {
    		return this.id;
    	}
    	...
    	@Column(name="COUNTRY_ID",insertable=false,updatable=false)
    	public Long getCountryID() {
    		return countryID;
    	}
    	...
    	@ManyToOne(cascade=CascadeType.PERSIST,fetch=FetchType.LAZY)
    	@JoinColumn(name="COUNTRY_ID")
    	public Country getCountry() {
    		return country;
    	}
    }
    Same kind of Repository and Service for City as well.

    In City create UI, using JQuery autocomplete showing the list of Countries to choose from. User selected value populated to countryID. But, when I'm trying to persist it throwing exception, not able to save child entity City with FK Country in database.

    Any help appreciated.

  2. #2
    Join Date
    May 2011
    Location
    Madrid (Spain)
    Posts
    101

    Default

    Hi, could you show the error log?

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •