问题
I get an input value from the user and store it into the DB. I use JPA to write into DB. If I need to store the input value into 2 columns in the DB, what is the annotation I must use?
Code below.
I need to store user input - (stored in Bean field UserOrderDetails.noOfItemsSelected) into 2 columns in the DB table NoOfItemsSelected and NoOfItemsDispatched. What annotation should I use?
The catch is that I do not want to add a field for NoOfItemsDispatched in the Entity Bean.
DB Table:
create table UserOrderDetails(
TransactionId varchar(255),
CreationDateTime datetime2(),
NoOfItemsSelected int,
NoOfItemsDispatched int
)
GO
My Entity Bean:
@Entity
@Table(name="UserOrderDetails")
public class UserOrderDetails {
@Id
private String transactionId;
private Timestamp CreationDateTime;
private int noOfItemsSelected;
//Getters and Setters
}
Controller class for Reference:
class UserOrderCreationController {
@RequestMapping(value = "/createUserOrder", method = RequestMethod.POST)
public ResponseEntity<?> createUserOrder(@RequestBody UserOrderDetails userOrderDetails , @RequestHeader HttpHeaders headers) throws Exception{
//Some business logic to handle the user Order
dbrepository.save(UserOrderDetails);
return new ResponseEntity<UserOrderDetails>(userOrderDetails, HttpStatus.CREATED);
}
}
Thanks
回答1:
As far as i know you just need to add annotations as below on the fields in the DAO layer entity class.if you have the same field names and column names these annotations are optional.
As the question states one value to multiple columns,before the the DAO.save is called you should be populating the value in both the fields.
@Entity
@Table(name="UserOrderDetails")
public class UserOrderDetails {
//Need to have identity generator of your wish
@Id
@Column(name = "TRANSACTION_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String transactionId;
private Timestamp CreationDateTime;
**@Column(name = "NO_OF_ITEMS_SELECTED")**
private int noOfItemsSelected;
**@Column(name = "NO_OF_ITEMS_DISP")**
private int noOfItemsDispatched;
//Getters and Setters
}
OR
Alternatively we can use Hibernate's @Formula annotation.Populate the one field which is coming from user request to the corresponding field and For the other column for which you can keep the same value by using @Formula.Look for some examples of @Formula
@Formula("noOfItemsSelected")
private float noOfItemsDispatched;
来源:https://stackoverflow.com/questions/50764815/map-one-value-to-multiple-columns-in-jpa