Spring MVC 和 Hibernate 是 Java 开发中常用的两个框架:
原因:
解决方法:
原因:
解决方法:
原因:
解决方法:
以下是一个简单的示例,展示如何使用 Spring MVC 和 Hibernate 进行基本的 CRUD 操作:
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("com.example.entity");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Getters and Setters
}
public interface UserDao {
List<User> findAll();
User findById(Long id);
void save(User user);
void delete(User user);
}
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory sessionFactory;
@Override
public List<User> findAll() {
return sessionFactory.getCurrentSession().createQuery("from User", User.class).getResultList();
}
@Override
public User findById(Long id) {
return sessionFactory.getCurrentSession().get(User.class, id);
}
@Override
public void save(User user) {
sessionFactory.getCurrentSession().saveOrUpdate(user);
}
@Override
public void delete(User user) {
sessionFactory.getCurrentSession().delete(user);
}
}
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserDao userDao;
@GetMapping
public String listUsers(Model model) {
model.addAttribute("users", userDao.findAll());
return "user-list";
}
@GetMapping("/{id}")
public String getUser(@PathVariable Long id, Model model) {
model.addAttribute("user", userDao.findById(id));
return "user-detail";
}
@PostMapping
public String saveUser(@ModelAttribute User user) {
userDao.save(user);
return "redirect:/users";
}
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
User user = userDao.findById(id);
userDao.delete(user);
return "redirect:/users";
}
}
希望这些信息对你有所帮助!如果有更多具体问题,欢迎继续提问。
领取专属 10元无门槛券
手把手带您无忧上云