JPA 中使用 @OneToMany 、@ManyToOne 等关系映射注解

JPA 做 ORM(Object Relational Mapping,对象关系映射)时,为了开发效率,通常会在实体类上用 hibernate 的关系关联注解。 包括:@OneToOne@OneToMany@ManyToOne@ManyToMany@JoinTable、以及 @JoinColumn 以及 OrderBy

JPA 中 @JoinColumn 与 关联注解之间用法

@JoinColumn 定义多个字段之间的关联关系,配合@OneToOne@ManyToOne 以及 @OneToMany一起使用

@Repeatable(JoinColumns.class)
@Target({
   ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface JoinColumn {
   
	// 关联字段(子)
    String name() default "";
	// 关键实体字段(父)),非必填
    String referencedColumnName() default "";

    boolean unique() default false;

    boolean nullable() default true;
    // 是否更新 插入操作
    boolean insertable() default true;

    boolean updatable() default true;

    String columnDefinition() default "";

    String table() default "";

    ForeignKey foreignKey() default @ForeignKey(ConstraintMode.PROVIDER_DEFAULT);
}

@OneToMany 注解为例,源代码如下

@Target({
   ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OneToMany {
   
    // 关联对象实体类
    Class targetEntity() default 
为了实现用户竞拍商品的功能,需要进行以下几个步骤: 1. 数据库设计 首先需要设计数据库表,包括用户表、商品表、竞拍记录表等。其中用户表和商品表是必须的,竞拍记录表用于记录用户对商品的竞拍情况。 2. 创建实体类 在 Java 代码中,需要创建对应的实体类来对应数据库中的表。可以使用 Spring Boot 的 JPA 技术来创建实体类与数据库表的映射关系。 3. 创建 DAO 层 DAO 层用于访问数据库,可以使用 Spring Boot 的 JPA 技术来操作数据库,包括增删改查等操作。 4. 创建 Service 层 Service 层用于定义业务逻辑,包括用户注册、登录、商品列表展示、竞拍商品等功能。 5. 创建 Controller 层 Controller 层用于接收用户请求,调用 Service 层的方法,并返回响应结果给前端展示。 下面是一个简单的示例代码: 1. 数据库设计 用户表: ```sql CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` 商品表: ```sql CREATE TABLE `product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `price` decimal(10,2) NOT NULL, `description` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` 竞拍记录表: ```sql CREATE TABLE `auction` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `productId` int(11) NOT NULL, `price` decimal(10,2) NOT NULL, `createTime` datetime NOT NULL, PRIMARY KEY (`id`), KEY `userId` (`userId`), KEY `productId` (`productId`), CONSTRAINT `auction_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `auction_ibfk_2` FOREIGN KEY (`productId`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` 2. 创建实体类 用户实体类: ```java @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false, unique = true) private String username; @Column(nullable = false) private String password; // getter and setter } ``` 商品实体类: ```java @Entity @Table(name = "product") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false) private String name; @Column(nullable = false) private BigDecimal price; private String description; // getter and setter } ``` 竞拍记录实体类: ```java @Entity @Table(name = "auction") public class Auction { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "userId") private User user; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "productId") private Product product; @Column(nullable = false) private BigDecimal price; @Column(nullable = false) private LocalDateTime createTime; // getter and setter } ``` 3. 创建 DAO 层 用户 DAO 接口: ```java public interface UserRepository extends JpaRepository<User, Integer> { User findByUsername(String username); } ``` 商品 DAO 接口: ```java public interface ProductRepository extends JpaRepository<Product, Integer> { } ``` 竞拍记录 DAO 接口: ```java public interface AuctionRepository extends JpaRepository<Auction, Integer> { List<Auction> findByProductIdOrderByPriceDescCreateTimeAsc(Integer productId); } ``` 4. 创建 Service 层 用户 Service 类: ```java @Service public class UserService { @Autowired private UserRepository userRepository; public User register(User user) { return userRepository.save(user); } public User login(String username, String password) { User user = userRepository.findByUsername(username); if (user != null && user.getPassword().equals(password)) { return user; } return null; } } ``` 商品 Service 类: ```java @Service public class ProductService { @Autowired private ProductRepository productRepository; public List<Product> list() { return productRepository.findAll(); } } ``` 竞拍记录 Service 类: ```java @Service public class AuctionService { @Autowired private AuctionRepository auctionRepository; public Auction bid(User user, Product product, BigDecimal price) { Auction auction = new Auction(); auction.setUser(user); auction.setProduct(product); auction.setPrice(price); auction.setCreateTime(LocalDateTime.now()); return auctionRepository.save(auction); } public List<Auction> history(Product product) { return auctionRepository.findByProductIdOrderByPriceDescCreateTimeAsc(product.getId()); } } ``` 5. 创建 Controller 层 用户 Controller 类: ```java @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @PostMapping("/register") public User register(@RequestBody User user) { return userService.register(user); } @PostMapping("/login") public User login(@RequestParam String username, @RequestParam String password) { return userService.login(username, password); } } ``` 商品 Controller 类: ```java @RestController @RequestMapping("/product") public class ProductController { @Autowired private ProductService productService; @GetMapping("/list") public List<Product> list() { return productService.list(); } } ``` 竞拍记录 Controller 类: ```java @RestController @RequestMapping("/auction") public class AuctionController { @Autowired private AuctionService auctionService; @PostMapping("/bid") public Auction bid(@RequestParam Integer userId, @RequestParam Integer productId, @RequestParam BigDecimal price) { User user = new User(); user.setId(userId); Product product = new Product(); product.setId(productId); return auctionService.bid(user, product, price); } @GetMapping("/history") public List<Auction> history(@RequestParam Integer productId) { Product product = new Product(); product.setId(productId); return auctionService.history(product); } } ``` 以上是一个简单的实现用户竞拍商品的示例代码,可以根据实际需求进行修改和完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张Python1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值