Skip to content

Commit d604888

Browse files
committed
Calculate entity property at INSERT or UPDATE time
1 parent 44334af commit d604888

File tree

3 files changed

+16
-19
lines changed

3 files changed

+16
-19
lines changed

HibernateSpringBootCalculatePropertyGenerated/src/main/java/com/bookstore/entity/Book.java

+2-7
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@ public class Book implements Serializable {
2626
// @Column(name="...", insertable=false)
2727

2828
@Generated(value = GenerationTime.ALWAYS)
29-
@Column(insertable = false, updatable = false,
30-
columnDefinition = "double AS (price - price * 0.25)")
29+
@Column(insertable = false, updatable = false /*, columnDefinition = "double AS (price - price * 0.25)"*/ )
3130
private double discount;
3231

3332
public Long getId() {
@@ -64,11 +63,7 @@ public void setPrice(double price) {
6463

6564
public double getDiscount() {
6665
return discount;
67-
}
68-
69-
public void setDiscount(double discount) {
70-
this.discount = discount;
71-
}
66+
}
7267

7368
@Override
7469
public String toString() {

HibernateSpringBootCalculatePropertyGenerated/src/main/resources/application.properties

+5-3
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@ spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNo
22
spring.datasource.username=root
33
spring.datasource.password=root
44

5-
spring.jpa.hibernate.ddl-auto=create
5+
#if you want to rely on columnDefinition then uncomment the following line
6+
#spring.jpa.hibernate.ddl-auto=create
7+
68
spring.jpa.show-sql=true
79

810
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
911

1012
spring.jpa.open-in-view=false
1113

12-
#spring.datasource.initialization-mode=always
13-
#spring.datasource.platform=mysql
14+
spring.datasource.initialization-mode=always
15+
spring.datasource.platform=mysql
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
-- Drop
2-
DROP TABLE IF EXISTS `bookstoredb`.`book`;
2+
DROP TABLE IF EXISTS bookstoredb.book;
33

44
-- Create
5-
CREATE TABLE `book` (
6-
`id` bigint(20) NOT NULL AUTO_INCREMENT,
7-
`discount` double GENERATED ALWAYS AS ((`price` - (`price` * 0.25))) VIRTUAL,
8-
`isbn` varchar(255) DEFAULT NULL,
9-
`price` double NOT NULL,
10-
`title` varchar(255) DEFAULT NULL,
11-
PRIMARY KEY (`id`)
12-
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
5+
CREATE TABLE book (
6+
id BIGINT NOT NULL AUTO_INCREMENT,
7+
discount DOUBLE GENERATED ALWAYS AS ((`price` - (`price` * 0.25))) STORED,
8+
isbn VARCHAR(255),
9+
price DOUBLE PRECISION NOT NULL,
10+
title VARCHAR(255),
11+
PRIMARY KEY (id)
12+
)

0 commit comments

Comments
 (0)