In my project I try yo use Spring data Jpa. My find methods(findById, findAll) works correctly, but delete and save method works with problems. Delete method delete only from duck table. Save doesn't work:
Exception in thread "main" org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find springdata.entities.FrogJpa with id 2; nested exception is javax.persistence.EntityNotFoundException: Unable to find springdata.entities.FrogJpa with id 2
I have 2 entities: Frog and Duck. Every ducks have 1 Frog(OneToOne). There are problems with entities relationship?
There are my entities class:
#Entity
#Table(name = "DUCKS")
public class DuckJpa implements Serializable {
#Id
private int id;
#Column(name = "NAME")
private String name;
#Column(name = "FLY")
private String flyBehavior;
#Column(name = "QUACK")
private String quackBehavior;
#OneToOne(optional = false)
#JoinColumn(name = "FROG_ID", unique = true, nullable = false, updatable = false)
private FrogJpa frogJpa;
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setFlyBehavior(String flyBehavior) {
this.flyBehavior = flyBehavior;
}
public void setQuackBehavior(String quackBehavior) {
this.quackBehavior = quackBehavior;
}
public void setFrogJpa(FrogJpa frogJpa) {
this.frogJpa = frogJpa;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getFlyBehavior() {
return flyBehavior;
}
public String getQuackBehavior() {
return quackBehavior;
}
public FrogJpa getFrogJpa() {
return frogJpa;
}
And Frog:
#Entity
#Table(name = "FROGS")
public class FrogJpa {
#OneToOne(optional = false, mappedBy = "frogJpa")
private DuckJpa duckJpa;
#Id
private int id;
#Column(name = "name")
private String name;
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setDuckJpa(DuckJpa duckJpa) {
this.duckJpa = duckJpa;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public DuckJpa getDuckJpa() {
return duckJpa;
}
}
My service class:
public interface DuckService {
List<DuckJpa> findAll();
Optional<DuckJpa> findById(Integer i);
DuckJpa save(DuckJpa duckJpa);
void delete(DuckJpa duckJpa);
}
And it's implementation:
#Service("springJpaDuckService")
#Transactional
public class DuckServiceImpl implements DuckService {
#Autowired
private DuckJpaRepository duckJpaRepository;
#Transactional(readOnly = true)
public List<DuckJpa> findAll() {
return new ArrayList<>(duckJpaRepository.findAll());
}
#Override
public Optional<DuckJpa> findById(Integer i) {
return duckJpaRepository.findById(i);
}
#Override
public DuckJpa save(DuckJpa duckJpa) {
duckJpaRepository.save(duckJpa);
return duckJpa;
}
#Override
public void delete(DuckJpa duckJpa) {
duckJpaRepository.delete(duckJpa);
}
Use #OneToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY).
For more information please refer What is cascading in Hibernate?
Related
I have 3 entities Movie, Show and Theatre with below relationship
Relations
#Entity
#Table(name = "theatre")
public class Theatre {
#Id
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "town")
private String town;
#OneToMany(mappedBy = "theatre", orphanRemoval = true)
private List<Show> shows = new ArrayList<>();
public List<Show> getShows() {
return shows;
}
public void setShows(List<Show> shows) {
this.shows = shows;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
#Entity
#Table(name = "show")
public class Show {
#Id
#Column(name = "id", nullable = false)
private Long id;
#ManyToOne
#JoinColumn(name = "theatre_id")
private Theatre theatre;
#ManyToOne
#JoinColumn(name = "movie_id")
private Movie movie;
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public Theatre getTheatre() {
return theatre;
}
public void setTheatre(Theatre theatre) {
this.theatre = theatre;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
#Entity
#Table(name = "movie")
public class Movie {
#Id
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "name")
private String name;
#OneToMany(mappedBy = "movie", orphanRemoval = true)
private List<Show> shows = new ArrayList<>();
public List<Show> getShows() {
return shows;
}
public void setShows(List<Show> shows) {
this.shows = shows;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Now when I try to fetch list of Theatres for a movie name I'm getting infinite nested result. As a result I'm getting StackOverflow error as well.
Is criteria query not suitable here? Or the relationship is wrong? Or criteria query is wrong itself.
Criteria query
public List<Theatre> findTheatresByMovieAndDate(String movieName) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Theatre> query = builder.createQuery(Theatre.class);
Root<Theatre> fromTheatres = query.from(Theatre.class);
Join<Theatre, Show> shows = fromTheatres.join("shows");
Join<Show, Movie> movie = shows.join("movie");
List<Predicate> conditions = new ArrayList<>();
conditions.add(builder.equal(movie.get("name"), movieName));
TypedQuery<Theatre> typedQuery = entityManager.createQuery(query
.select(fromTheatres)
.where(conditions.toArray(new Predicate[] {}))
.orderBy(builder.asc(fromTheatres.get("id")))
.distinct(true)
);
return typedQuery.getResultList();
}
Thanks in advance
I am new to the JPA world. Here I have tried to make a simple POS. The problem is that when there is no predefined value in tables although the PK is auto-incremented, data is not being inserted into DB. But if I set a predefined row into the tables then there are no issues and data is being inserted successfully. please help me.
The following are my Java classes, and I am using Mysql for DB.
#Entity
#Table(name = "card_payment")
public class Card_payment {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "order_id")
private Orders order;
#Column(name = "issuing_bank")
String issuing_bank;
#Column(name = "card_type")
String card_type;
#Column(name = "card_expiry_date")
String card_expiry_date;
#Column(name = "amount")
int amount;
public Card_payment() {
super();
}
public Orders getOrder() {
return order;
}
public void setOrder(Orders order) {
this.order = order;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIssuing_bank() {
return issuing_bank;
}
public void setIssuing_bank(String issuing_bank) {
this.issuing_bank = issuing_bank;
}
public String getCard_type() {
return card_type;
}
public void setCard_type(String card_type) {
this.card_type = card_type;
}
public String getCard_expiry_date() {
return card_expiry_date;
}
public void setCard_expiry_date(String card_expiry_date) {
this.card_expiry_date = card_expiry_date;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
#Entity
#Table(name = "customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#Column(name = "name")
String name;
#Column(name = "mobile_no")
long mobile_no;
#Column(name = "address")
String address;
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL,
fetch=FetchType.LAZY)
private List<Orders> orders;;
public Customer() {
super();
}
public List<Orders> getOrders() {
return orders;
}
public void setOrders(List<Orders> orders) {
this.orders = orders;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getMobile_no() {
return mobile_no;
}
public void setMobile_no(long mobile_no) {
this.mobile_no = mobile_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
#Entity
#Table(name = "Item")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#Column(name = "name")
String name;
#Column(name = "unit")
String unit;
#Column(name = "stock_quantity")
int stock_quantity;
#Column(name = "reorder_level")
int reorder_level;
#Column(name = "unit_price")
int unit_price;
#Column(name = "tax_percentage")
float tax_percentage;
#OneToMany(mappedBy = "item", cascade = CascadeType.ALL,
fetch=FetchType.LAZY)
private List<Orderline> orderLines;
public Item() {
super();
}
public List<Orderline> getOrderLines() {
return orderLines;
}
public void setOrderLines(List<Orderline> orderLines) {
this.orderLines = orderLines;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
public int getStock_quantity() {
return stock_quantity;
}
public void setStock_quantity(int stock_quantity) {
this.stock_quantity = stock_quantity;
}
public int getReorder_level() {
return reorder_level;
}
public void setReorder_level(int reorder_level) {
this.reorder_level = reorder_level;
}
public int getUnit_price() {
return unit_price;
}
public void setUnit_price(int unit_price) {
this.unit_price = unit_price;
}
public float getTax_percentage() {
return tax_percentage;
}
public void setTax_percentage(float tax_percentage) {
this.tax_percentage = tax_percentage;
}
}
#Entity
#Table(name = "OrderLine")
public class Orderline {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#ManyToOne
#JoinColumn(name = "itemId")
private Item item;
#ManyToOne
#JoinColumn(name = "orderId")
private Orders orders;
#Column(name = "unit_cost")
float unit_cost;
#Column(name = "unit")
int unit;
#Column(name = "tax_percentage")
float tax_percentage;
#Column(name = "quantity")
int quantity;
#Column(name = "amount")
int amount;
#Column(name = "tax_amount")
float tax_amount;
#Column(name = "line_total")
int line_total;
public Orderline() {
super();
}
public Item getItem() {
return item;
}
public void setItem(Item item) {
this.item = item;
}
public Orders getOrders() {
return orders;
}
public void setOrders(Orders orders) {
this.orders = orders;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public float getUnit_cost() {
return unit_cost;
}
public void setUnit_cost(float unit_cost) {
this.unit_cost = unit_cost;
}
public int getUnit() {
return unit;
}
public void setUnit(int unit) {
this.unit = unit;
}
public float getTax_percentage() {
return tax_percentage;
}
public void setTax_percentage(float tax_percentage) {
this.tax_percentage = tax_percentage;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public float getTax_amount() {
return tax_amount;
}
public void setTax_amount(float tax_amount) {
this.tax_amount = tax_amount;
}
public int getLine_total() {
return line_total;
}
public void setLine_total(int line_total) {
this.line_total = line_total;
}
#Entity
#Table(name = "orders")
public class Orders {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
int id;
#ManyToOne
#JoinColumn(name = "customerId")
private Customer customer;
#Column(name = "order_date")
String order_date;
#Column(name = "delivery_address")
String delivery_address;
#Column(name = "total")
long total;
#OneToMany(mappedBy = "orders", cascade = CascadeType.ALL,
fetch=FetchType.LAZY)
private List<Orderline> orderlines;
#OneToOne(mappedBy = "order")
private Cash_payment cash_payment;
#OneToOne(mappedBy = "order")
private Card_payment card_payment;
#OneToOne(mappedBy = "order")
private Cheque_payment cheque_payment;
public Orders() {
super();
}
public Cash_payment getCash_payment() {
return cash_payment;
}
public void setCash_payment(Cash_payment cash_payment) {
this.cash_payment = cash_payment;
}
public Card_payment getCard_payment() {
return card_payment;
}
public void setCard_payment(Card_payment card_payment) {
this.card_payment = card_payment;
}
public Cheque_payment getCheque_payment() {
return cheque_payment;
}
public void setCheque_payment(Cheque_payment cheque_payment) {
this.cheque_payment = cheque_payment;
}
public List<Orderline> getOrderlines() {
return orderlines;
}
public void setOrderlines(List<Orderline> orderlines) {
this.orderlines = orderlines;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrder_date() {
return order_date;
}
public void setOrder_date(String order_date) {
this.order_date = order_date;
}
public String getDelivery_address() {
return delivery_address;
}
public void setDelivery_address(String delivery_address) {
this.delivery_address = delivery_address;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
}
public class JPAExample {
private static EntityManager entityManager = EntityManagerUtil.getEntityManager();
public static void main(String[] args) {
JPAExample example = new JPAExample();
entityManager.getTransaction().begin();
Orders order = new Orders();
order.setOrder_date("2019/05/05");
order.setTotal(1000);
order.setDelivery_address("kolkata");
Item item = new Item();
item.setName("cream");
item.setReorder_level(10);
item.setUnit_price(10);
item.setUnit("kg");
item.setTax_percentage((float) 12.5);
item.setStock_quantity(20);
item.setReorder_level(5);
Orderline orderline = new Orderline();
orderline.setAmount(1);
orderline.setItem(item);
orderline.setLine_total(200);
orderline.setQuantity(1);
List<Orderline> orderlns = new ArrayList<>();
orderlns.add(orderline);
item.setOrderLines(orderlns);
Customer customer = new Customer();
customer.setId(1234);
customer.setName("Tanusha");
customer.setMobile_no(Long.valueOf("9609"));
customer.setAddress("u-86, garia");
orderline.setOrders(order);
List<Orderline> orderLinesList = new ArrayList<>();
orderLinesList.add(orderline);
order.setOrderlines(orderLinesList);
order.setCustomer(customer);
List<Orders> orderList = new ArrayList<>();
orderList.add(order);
customer.setOrders(orderList);
Card_payment cp = new Card_payment();
cp.setAmount(200);
cp.setCard_expiry_date("2019/05/05");
cp.setCard_type("visa");
cp.setIssuing_bank("SBI");
cp.setOrder(order);
order.setCard_payment(cp);
entityManager.merge(order);
try {
entityManager.getTransaction().commit();
} catch (Exception e) {
entityManager.getTransaction().rollback();
}
}
}
good day everyone,
i have this project where i use the ModelMapper to mat my entities to DTOs and vise-versa, and also have a class with #ElementCollection relation.
the mapper seems to work fine for all other methods and it just output the entity as i want, however when it comes to delete mapping i get the following error printed along with a 500 http status. here's the error:
"ModelMapper mapping errors:\r\n\r\n1) Converter org.modelmapper.internal.converter.CollectionConverter#ddb7bc7 failed to convert java.util.List to java.util.List.\r\n\r\n1 error"
here is code:
the entity class:
#Entity
#Table(name = "quiz_engines")
#EntityListeners(AuditingEntityListener.class)
#JsonIgnoreProperties(
value = {"lastModified"},
allowGetters = true
)
public class Engine implements Model {
#Id
#Column(name = "engine_id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY,optional = false, targetEntity = com.QCMGenerator.QCMGenerator.Model.Test.class)
#JoinColumn(name = "test_id", referencedColumnName = "test_id", nullable = false, updatable = false)
#OnDelete(action = OnDeleteAction.NO_ACTION)
#JsonIgnore
private Test test;
#Column(name = "quiz_name", nullable = false)
#NotNull
private String name;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "last_modified", nullable = false)
#LastModifiedDate
private Date lastModified;
#ElementCollection
#CollectionTable(name = "engine_constraints", joinColumns = #JoinColumn(name = "engine_id"))
private List<EngineConstraint> constraints;
public Engine() {
}
public Engine(#NotNull String name, List<EngineConstraint> constraints) {
this.name = name;
this.constraints = constraints;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the DTO class:
public class EngineDTO implements ModelDTO {
private Long id;
#JsonIgnore
private TestDTO test;
private String name;
private Date lastModified;
private List<EngineConstraint> constraints;
public EngineDTO() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public TestDTO getTest() {
return test;
}
public void setTest(TestDTO test) {
this.test = test;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public List<EngineConstraint> getConstraints() {
return constraints;
}
public void setConstraints(List<EngineConstraint> constraints) {
this.constraints = constraints;
}
}
the Delete Controller:
#DeleteMapping("/{engineID}")
public ResponseEntity<NonPaginatedResponse> deleteEngine(
#PathVariable(value = "testID") Long testID,
#PathVariable(value = "engineID") Long engineID
){
if(!testRepo.existsById(testID)){
throw new ResourceNotFoundException("No test with the ID '"+testID+"' was found...");
}
return engineRepo.findById(engineID).map(engineFound -> {
engineRepo.delete(engineFound);
return ResponseEntity.status(HttpStatus.OK).body(
ResponseBodyBuilder.getSingleResponse(
convertToDTO(engineFound),
new ModelDTO[]{ convertToDTO(testRepo.findById(testID).get()) },
"delete"
)
);
}
).orElseThrow(
() -> new ResourceNotFoundException("No Engine with the ID '"+engineID+"' was found...")
);
}
hope you guys can help with this one, thank for your time everyone and have a good day.
i have two entity classes named Qa.java and Answeres.java
my Qa entity consists of lists of answers.
Qa.Java
#Entity
#Table(name = "qa")
public class Qa {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
private String question;
private String type;
private String description;
private String param;
private int maxlength;
#OneToMany(mappedBy = "qa", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Answers> answersList = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParam() {
return param;
}
public void setParam(String param) {
this.param = param;
}
public int getMaxlength() {
return maxlength;
}
public void setMaxlength(int maxlength) {
this.maxlength = maxlength;
}
public List<Answers> getAnswersList() {
return answersList;
}
public void setAnswersList(List<Answers> answersList) {
this.answersList = answersList;
}
}
Answers.java
#Entity
#Table(name = "answers")
public class Answers {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String ans_label;
private int ans_value;
private int ans_weightage;
private int is_default;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "question_id", referencedColumnName = "id",nullable = false)
private Qa qa;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAns_label() {
return ans_label;
}
public void setAns_label(String ans_label) {
this.ans_label = ans_label;
}
public int getAns_value() {
return ans_value;
}
public void setAns_value(int ans_value) {
this.ans_value = ans_value;
}
public int getAns_weightage() {
return ans_weightage;
}
public void setAns_weightage(int ans_weightage) {
this.ans_weightage = ans_weightage;
}
public int getIs_default() {
return is_default;
}
public void setIs_default(int is_default) {
this.is_default = is_default;
}
public Qa getQa() {
return qa;
}
public void setQa(Qa qa) {
this.qa = qa;
}
}
My controller from where i am trying to insert data.
TableDataController.java
#Controller
public class TabletDataController {
#Autowired
QaRepository qaRepository;
#RequestMapping(value = "/saveApiData", method = RequestMethod.GET)
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
answersArrayList.add(answers);
qa.setAnswersList(answersArrayList);
qaRepository.save(qa);
}
}
my qaRepository extends JpaRepository. so whenever i call this api i get an error of com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'question_id' cannot be null
what am i doing wrong?
You have a bidirectional OneToMany relationship, so you need to manually maintain both sides of the relationship. Here you are only setting the Qa side with qa.setAnswersList(answersArrayList);
You need to set the other side of your relationship manually. add:
answers.setQa(qa);
before you save your list
code as follow
public void saveApiData(){
Qa qa = new Qa();
qa.setParam("");
qa.setType("input_spinner");
qa.setDescription("");
qa.setQuestion("व्यक्तिको पहिलो नाम ?");
ArrayList<Answers> answersArrayList = new ArrayList<>();
Answers answers = new Answers();
answers.setAns_label("नेपाली");
answers.setAns_value(1);
answers.setAns_weightage(0);
answers.setIs_default(0);
answers.setQa(qa);
answersArrayList.add(answers);
qa.setAnswersList(answersArrayList);
qaRepository.save(qa);
}
when you save.you should Cascade save.Your annotations configure the relationship of the associated tables but also to associate them when they are saved
I'm developing an application using java with hibernate 4.2.6 and spring 4.0.1. My application is a REST FULL application. for this I use jackson. My entities are as follow:
Calk.java:
#Entity
public class Calk {
#Id
#GeneratedValue
private Long id;
#OneToMany(mappedBy="calk", fetch=FetchType.LAZY)
List<BaseLayer> baseLayer = new ArrayList<BaseLayer>();
public void addBaseLayer(BaseLayer baseLayer){
this.baseLayer.add(baseLayer);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JsonIgnore
public List<BaseLayer> getBaseLayer() {
return baseLayer;
}
public void setBaseLayer(List<BaseLayer> baseLayer) {
this.baseLayer = baseLayer;
}
}
BaseLayer.java:
#Entity
#Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="layer")
#JsonSubTypes(
{
#JsonSubTypes.Type(value=PointLayer.class, name="point")
})
#DiscriminatorValue("BaseLayerDiscriminator")
public class BaseLayer {
#Id
#GeneratedValue
protected Long gid;
#ManyToOne(fetch = FetchType.LAZY)
protected Calk calk;
public Long getGid(){
return gid;
}
public void setGid(Long gid){
this.gid = gid;
}
#JsonIgnore
public Calk getCalk(){
return calk;
}
public void setCalk(Calk calk){
this.calk = calk;
}
}
Now I have a class that extends from BaseLayer.java as follow:
PointLayer.java:
#Entity
#DiscriminatorValue("PointDiscriminator")
public class PointLayer extends BaseLayer{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now I create a json as follow and then send it to a controller:
{"layer": "point", "calk":{"id":1}, "name": "itsme"}
Now the controller defines as follow:
#RequestMapping("\test")
public String test(#RequestBody BaseLayer baseLayer){
System.out.println(baseLayer.getName());// this print "itsme"
Calk calk = baseLayer.getCalk();//it return null
if(calk == null)
return "its null";
else
return "its not null";
}
when we call the controller it return its not null. The calk should not be null.
Where is the problem?
Update:
When I remove #JsonIgnore at getCalk, It work fine. But Why? I want to ignore getCalk but NOT ignore setCalk.
#JsonIgnore in follow:
#JsonIgnore
public List<BaseLayer> getBaseLayer() {
return baseLayer;
}
set Ignore to following by default:
public void setBaseLayer(List<BaseLayer> baseLayer) {
this.baseLayer = baseLayer;
}
You must add #JsonProperty("baseLayer") On top of set function as follow:
#JsonProperty("baseLayer")
public void setBaseLayer(List<BaseLayer> baseLayer) {
this.baseLayer = baseLayer;
}