Example: Purchase a trans_sale item
This example is to realize the purchase of goods, simulate the user to place an order, add sales records to the order table, and reduce inventory from the product table.
Implementation steps:
Step0: Create database tables
Create two database tables sale, goods
sale sales table:
goods table:
Goods table data:
Step1: maven depends on pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.26</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.26</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.26</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
</dependencies>
<!--插件:-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
Step2: Create entity classes
Create entity classes Sale and Goods
Step3: Define the dao interface
Define two dao interfaces SaleDao and GoodsDao
SaleDao:
GoodsDao :
Step4: Define the sql mapping file corresponding to the dao interface
SaleDao.xml
GoodsDao.xml
Step5: Define the exception class
Define the exception class NotEnoughException that may be thrown by the service layer
Step6: Define the Service interface
Define the Service interface BuyGoodsService
Step7: Define the implementation class of service
Define the implementation class BuyGoodsServiceImpl of the service layer interface
1) Class definition
2) Dao attribute
3) Buy method
Step8: Modify the content of the Spring configuration file
Declare the Mybatis object
Declare business layer objects
Step9: Define the test class
Define the test class MyTest. It is now ready to run without a transactional proxy
Run the program and view the database:
Test code can be of three types:
① Normal purchase [id and amount match]
② There is no such product【there is no id in the library】
③ Insufficient inventory [amount is greater than the original amount]