本文目录导读:

- 图书管理系统(基础CRUD案例)
- 用户认证系统(Spring Security案例)
- 在线商城系统(Spring Boot + MyBatis案例)
- 知识管理平台(全文搜索案例)
- 微服务消息队列案例(RabbitMQ)
- 项目架构建议
我来为你提供几个Java知识库的典型案例,涵盖不同应用场景。
图书管理系统(基础CRUD案例)
// 实体类
public class Book {
private Long id;
private String title;
private String author;
private String isbn;
private double price;
private int stock;
private Date publishDate;
// 构造器、getter/setter省略
}
// 数据访问层(DAO)
@Repository
public class BookDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
// 添加图书
public int addBook(Book book) {
String sql = "INSERT INTO books (title, author, isbn, price, stock) VALUES (?, ?, ?, ?, ?)";
return jdbcTemplate.update(sql,
book.getTitle(),
book.getAuthor(),
book.getIsbn(),
book.getPrice(),
book.getStock());
}
// 查询所有图书
public List<Book> findAll() {
String sql = "SELECT * FROM books";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class));
}
// 根据ID查询
public Book findById(Long id) {
String sql = "SELECT * FROM books WHERE id = ?";
return jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<>(Book.class), id);
}
// 更新图书
public int updateBook(Book book) {
String sql = "UPDATE books SET title=?, author=?, isbn=?, price=? WHERE id=?";
return jdbcTemplate.update(sql,
book.getTitle(),
book.getAuthor(),
book.getIsbn(),
book.getPrice(),
book.getId());
}
// 删除图书
public int deleteBook(Long id) {
String sql = "DELETE FROM books WHERE id = ?";
return jdbcTemplate.update(sql, id);
}
}
// 服务层
@Service
public class BookService {
@Autowired
private BookDAO bookDAO;
@Transactional
public boolean borrowBook(Long bookId, Long userId) {
Book book = bookDAO.findById(bookId);
if (book.getStock() <= 0) {
throw new RuntimeException("库存不足");
}
// 更新库存
book.setStock(book.getStock() - 1);
bookDAO.updateBook(book);
// 记录借阅信息
return true;
}
}
用户认证系统(Spring Security案例)
// 用户实体
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
private String email;
private boolean enabled;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();
// getter/setter省略
}
// 自定义UserDetailsService
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
return org.springframework.security.core.userdetails.User
.builder()
.username(user.getUsername())
.password(user.getPassword())
.roles(user.getRoles().stream()
.map(Role::getName)
.toArray(String[]::new))
.build();
}
}
// JWT令牌服务
@Component
public class JwtTokenService {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration}")
private Long expiration;
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put("roles", userDetails.getAuthorities());
return Jwts.builder()
.setClaims(claims)
.setSubject(userDetails.getUsername())
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expiration))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
public String extractUsername(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody()
.getSubject();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername())
&& !isTokenExpired(token));
}
}
在线商城系统(Spring Boot + MyBatis案例)
// Order实体
public class Order {
private Long orderId;
private Long userId;
private List<OrderItem> items;
private BigDecimal totalAmount;
private String status; // PENDING, PAID, SHIPPED, COMPLETED
private String shippingAddress;
private Date createTime;
}
// OrderMapper接口
@Mapper
public interface OrderMapper {
@Insert("INSERT INTO orders (user_id, total_amount, status, shipping_address, create_time) " +
"VALUES (#{userId}, #{totalAmount}, #{status}, #{shippingAddress}, NOW())")
@Options(useGeneratedKeys = true, keyProperty = "orderId")
int insertOrder(Order order);
@Insert("<script>" +
"INSERT INTO order_items (order_id, product_id, quantity, price) VALUES " +
"<foreach collection='items' item='item' separator=','>" +
"(#{orderId}, #{item.productId}, #{item.quantity}, #{item.price})" +
"</foreach>" +
"</script>")
int insertOrderItems(Order order);
@Select("SELECT * FROM orders WHERE user_id = #{userId} ORDER BY create_time DESC")
List<Order> findByUserId(Long userId);
@Select("SELECT * FROM order_items WHERE order_id = #{orderId}")
List<OrderItem> findItemsByOrderId(Long orderId);
}
// 订单服务
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private ProductMapper productMapper;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Transactional
public Order createOrder(Long userId, List<CartItem> cartItems, String address) {
// 1. 校验库存
for (CartItem item : cartItems) {
Product product = productMapper.findById(item.getProductId());
if (product.getStock() < item.getQuantity()) {
throw new InsufficientStockException("商品库存不足: " + product.getName());
}
}
// 2. 计算总价
BigDecimal total = BigDecimal.ZERO;
List<OrderItem> orderItems = new ArrayList<>();
for (CartItem cartItem : cartItems) {
Product product = productMapper.findById(cartItem.getProductId());
OrderItem orderItem = new OrderItem();
orderItem.setProductId(product.getId());
orderItem.setQuantity(cartItem.getQuantity());
orderItem.setPrice(product.getPrice());
total = total.add(product.getPrice()
.multiply(BigDecimal.valueOf(cartItem.getQuantity())));
orderItems.add(orderItem);
}
// 3. 创建订单
Order order = new Order();
order.setUserId(userId);
order.setItems(orderItems);
order.setTotalAmount(total);
order.setStatus("PENDING");
order.setShippingAddress(address);
// 4. 保存订单
orderMapper.insertOrder(order);
orderMapper.insertOrderItems(order);
// 5. 扣减库存
for (CartItem item : cartItems) {
productMapper.decreaseStock(item.getProductId(), item.getQuantity());
}
return order;
}
// 使用Redis缓存热门订单
public List<Order> getRecentOrders(Long userId) {
String cacheKey = "user:orders:" + userId;
String cached = redisTemplate.opsForValue().get(cacheKey);
if (cached != null) {
return JSON.parseArray(cached, Order.class);
}
List<Order> orders = orderMapper.findByUserId(userId);
redisTemplate.opsForValue().set(cacheKey,
JSON.toJSONString(orders),
Duration.ofMinutes(10));
return orders;
}
}
知识管理平台(全文搜索案例)
// Elasticsearch文档模型
@Document(indexName = "knowledge", type = "article", shards = 2)
public class KnowledgeArticle {
@Id
private String id;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String title;
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String content;
@Field(type = FieldType.Keyword)
private String category;
@Field(type = FieldType.Keyword)
private List<String> tags;
@Field(type = FieldType.Date)
private Date publishTime;
@Field(type = FieldType.Integer)
private int viewCount;
}
// 搜索服务
@Service
public class KnowledgeSearchService {
@Autowired
private ElasticsearchRestTemplate esTemplate;
public Page<KnowledgeArticle> search(String keyword, int page, int size) {
// 构建搜索条件
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.boolQuery()
.should(QueryBuilders.matchQuery("title", keyword).boost(2.0f))
.should(QueryBuilders.matchQuery("content", keyword))
.minimumShouldMatch(1))
.withPageable(PageRequest.of(page, size))
.withSort(SortBuilders.fieldSort("_score").order(SortOrder.DESC))
.build();
return esTemplate.queryForPage(searchQuery, KnowledgeArticle.class);
}
// 相关文章推荐
public List<KnowledgeArticle> recommendSimilar(String articleId, int limit) {
KnowledgeArticle current = esTemplate.get(articleId, KnowledgeArticle.class);
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.moreLikeThisQuery()
.addLikeText(current.getTitle())
.addLikeText(current.getContent())
.minTermFrequency(1)
.maxQueryTerms(12))
.withPageable(PageRequest.of(0, limit))
.build();
Page<KnowledgeArticle> similar = esTemplate.queryForPage(
searchQuery, KnowledgeArticle.class);
return similar.getContent().stream()
.filter(a -> !a.getId().equals(articleId))
.collect(Collectors.toList());
}
}
// 索引管理
@Component
public class KnowledgeIndexManager {
@Autowired
private ElasticsearchRestTemplate esTemplate;
@PostConstruct
public void initIndex() throws IOException {
if (!esTemplate.indexExists(KnowledgeArticle.class)) {
esTemplate.createIndex(KnowledgeArticle.class);
esTemplate.putMapping(KnowledgeArticle.class);
}
}
// 批量索引文档
public void bulkIndex(List<KnowledgeArticle> articles) {
for (KnowledgeArticle article : articles) {
esTemplate.save(article);
}
}
}
微服务消息队列案例(RabbitMQ)
// 消息生产者
@Component
public class OrderMessageProducer {
@Autowired
private RabbitTemplate rabbitTemplate;
public void sendOrderCreatedMessage(Order order) {
OrderEvent event = new OrderEvent();
event.setOrderId(order.getOrderId());
event.setUserId(order.getUserId());
event.setTotalAmount(order.getTotalAmount());
event.setEventType("ORDER_CREATED");
event.setTimestamp(new Date());
// 发送到订单交换器
rabbitTemplate.convertAndSend(
"order.exchange",
"order.created",
event
);
// 发送延迟消息(超时未支付检查)
rabbitTemplate.convertAndSend(
"order.delay.exchange",
"order.timeout",
event,
message -> {
message.getMessageProperties().setExpiration(
String.valueOf(30 * 60 * 1000)); // 30分钟
return message;
}
);
}
}
// 消息消费者
@Component
@Slf4j
public class OrderMessageConsumer {
@Autowired
private OrderService orderService;
@Autowired
private NotificationService notificationService;
@RabbitListener(queues = "order.created.queue")
public void handleOrderCreated(OrderEvent event) {
log.info("收到订单创建消息: {}", event.getOrderId());
// 处理业务逻辑
notificationService.sendConfirmation(
event.getUserId(),
event.getOrderId()
);
}
@RabbitListener(queues = "order.timeout.queue")
public void handleOrderTimeout(OrderEvent event) {
log.info("订单超时检查: {}", event.getOrderId());
orderService.cancelTimeoutOrder(event.getOrderId());
}
@RabbitListener(queues = "notification.queue")
public void handleNotification(NotificationMessage message) {
// 发送各种通知(短信、邮件、推送)
notificationService.sendNotification(message);
}
}
项目架构建议
知识库项目结构:
├── src/main/java
│ ├── config/ # 配置类
│ │ ├── SecurityConfig.java
│ │ ├── RedisConfig.java
│ │ ├── RabbitMQConfig.java
│ │ └── ElasticsearchConfig.java
│ ├── controller/ # 控制器层
│ ├── service/ # 服务层
│ │ ├── impl/
│ ├── repository/ # 数据访问层
│ ├── entity/ # 实体类
│ ├── dto/ # 数据传输对象
│ ├── exception/ # 异常处理
│ ├── utils/ # 工具类
│ └── task/ # 定时任务
├── src/main/resources
│ ├── application.yml # 配置文件
│ ├── mapper/ # MyBatis映射文件
│ └── templates/ # 模板文件
这些案例涵盖了Java开发的常见场景,从基础CRUD到高级分布式系统都有涉及,根据实际需求,可以选择合适的技术栈进行开发。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播