在本文中,我想研究一个Spring MVC + Hibernate + Maven用法的示例。 这套技术暗含领域领域的基础知识。 因此,我将尝试详细解释所有重要时刻。 其他没有主题的内容将提供指向更多详细信息源的链接。 在文章的结尾,我将发布GitHub的链接。
目标
基于Spring MVC,Hibernate,Maven创建示例Web应用程序。 界面将基于HTML。 该应用程序将支持所有CRUD操作:创建,读取,更新,删除 。 通常,我将使用MySQL作为数据库。 的
该应用程序将与足球俱乐部实体一起使用,因此请准备好将本教程应用于运动方向。
准备工作
我将在数据库中需要一个表,下面是创建它的代码:
CREATE TABLE `teams` (`id` int(6) NOT NULL AUTO_INCREMENT,`name` varchar(40) NOT NULL,`rating` int(6) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
该表将在应用程序中以类表示:
@Entity
@Table(name="teams")
public class Team {@Id@GeneratedValueprivate Integer id;private String name;private Integer rating;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getRating() {return rating;}public void setRating(Integer rating) {this.rating = rating;}}
然后,我需要在IDE中创建一个新的Maven Web项目(我使用Eclipse)。 我将省略创建的详细信息,您可以在我的一篇有关Maven Web Project创建的文章中阅读有关此内容的信息 。 这是pom.xml文件的链接。 第一个重要的停止点是WebAppConfig.java文件,因此让我们考虑一下:
@Configuration
@ComponentScan("com.sprhib")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class WebAppConfig {private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";private static final String PROPERTY_NAME_DATABASE_URL = "db.url";private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";@Resourceprivate Environment env;@Beanpublic DataSource dataSource() {DriverManagerDataSource dataSource = new DriverManagerDataSource();dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));return dataSource;}@Beanpublic LocalSessionFactoryBean sessionFactory() {LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();sessionFactoryBean.setDataSource(dataSource());sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(
PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));sessionFactoryBean.setHibernateProperties(hibProperties());return sessionFactoryBean;}private Properties hibProperties() {Properties properties = new Properties();properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));return properties; }@Beanpublic HibernateTransactionManager transactionManager() {HibernateTransactionManager transactionManager = new HibernateTransactionManager();transactionManager.setSessionFactory(sessionFactory().getObject());return transactionManager;}@Beanpublic UrlBasedViewResolver setupViewResolver() {UrlBasedViewResolver resolver = new UrlBasedViewResolver();resolver.setPrefix("/WEB-INF/pages/");resolver.setSuffix(".jsp");resolver.setViewClass(JstlView.class);return resolver;}}
在文件的开头,您可以看到@EnableTransactionManagement,它启用了Spring的注释驱动的事务管理功能。 注释@PropertySource(“ classpath:application.properties”)–插入位于资源文件夹中的属性文件。 请注意以下三个bean:transactionManager,sessionFactory和dataSource。 这些bean提供事务管理。 有关更多信息,请阅读我有关Hibernate功能的文章。
#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/hibnatedb
db.username=hibuser
db.password=root#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.sprhib.model
多数民众赞成在所有与项目准备有关。 此外,我将向您展示DAO和服务层。
DAO和服务层
这是DAO和服务的接口和实现:
public interface TeamDAO {public void addTeam(Team team);public void updateTeam(Team team);public Team getTeam(int id);public void deleteTeam(int id);public ListgetTeams();}
DAO接口的实现:
@Repository
public class TeamDAOImpl implements TeamDAO {@Autowiredprivate SessionFactory sessionFactory;private Session getCurrentSession() {return sessionFactory.getCurrentSession();}public void addTeam(Team team) {getCurrentSession().save(team);}public void updateTeam(Team team) {Team teamToUpdate = getTeam(team.getId());teamToUpdate.setName(team.getName());teamToUpdate.setRating(team.getRating());getCurrentSession().update(teamToUpdate);}public Team getTeam(int id) {Team team = (Team) getCurrentSession().get(Team.class, id);return team;}public void deleteTeam(int id) {Team team = getTeam(id);if (team != null)getCurrentSession().delete(team);}@SuppressWarnings("unchecked")public ListgetTeams() {return getCurrentSession().createQuery("from Team").list();}}
注释@Repository指示带注释的类是“ DAO”。
public interface TeamService {public void addTeam(Team team);public void updateTeam(Team team);public Team getTeam(int id);public void deleteTeam(int id);public ListgetTeams();}
服务接口的实现:
@Service
@Transactional
public class TeamServiceImpl implements TeamService {@Autowiredprivate TeamDAO teamDAO;public void addTeam(Team team) {teamDAO.addTeam(team); }public void updateTeam(Team team) {teamDAO.updateTeam(team);}public Team getTeam(int id) {return teamDAO.getTeam(id);}public void deleteTeam(int id) {teamDAO.deleteTeam(id);}public ListgetTeams() {return teamDAO.getTeams();}}
注释@Service表示带注释的类是“服务”。 注释@Transactional描述方法或类上的事务属性。
控制器和JSP
由于我将介绍所有CRUD操作,因此本章将有些长。 我将从基本控制器开始,它可用于主页:
@Controller
public class LinkController {@RequestMapping(value="/")public ModelAndView mainPage() {return new ModelAndView("home");}@RequestMapping(value="/index")public ModelAndView indexPage() {return new ModelAndView("home");}}
这很简单,这里是其JSP文件:
...
<h1>Home page</h1>
<p>
${message}<br>
<a href="${pageContext.request.contextPath}/team/add.html">Add new team</a><br>
<a href="${pageContext.request.contextPath}/team/list.html">Team list</a><br>
</p>
...
这是一个怪物级的应用程序的主控制器:
@Controller
public class TeamController {@Autowiredprivate TeamService teamService;@RequestMapping(value="/team/add")public ModelAndView addTeamPage() {ModelAndView modelAndView = new ModelAndView("add-team-form");modelAndView.addObject("team", new Team());return modelAndView;}@RequestMapping(value="/team/add/process")public ModelAndView addingTeam(@ModelAttribute Team team) {ModelAndView modelAndView = new ModelAndView("home");teamService.addTeam(team);String message = "Team was successfully added.";modelAndView.addObject("message", message);return modelAndView;}@RequestMapping(value="/team/list")public ModelAndView listOfTeams() {ModelAndView modelAndView = new ModelAndView("list-of-teams");Listteams = teamService.getTeams();modelAndView.addObject("teams", teams);return modelAndView;}@RequestMapping(value="/team/edit/{id}", method=RequestMethod.GET)public ModelAndView editTeamPage(@PathVariable Integer id) {ModelAndView modelAndView = new ModelAndView("edit-team-form");Team team = teamService.getTeam(id);modelAndView.addObject("team",team);return modelAndView;}@RequestMapping(value="/team/edit/{id}", method=RequestMethod.POST)public ModelAndView edditingTeam(@ModelAttribute Team team, @PathVariable Integer id) {ModelAndView modelAndView = new ModelAndView("home");teamService.updateTeam(team);String message = "Team was successfully edited.";modelAndView.addObject("message", message);return modelAndView;}@RequestMapping(value="/team/delete/{id}", method=RequestMethod.GET)public ModelAndView deleteTeam(@PathVariable Integer id) {ModelAndView modelAndView = new ModelAndView("home");teamService.deleteTeam(id);String message = "Team was successfully deleted.";modelAndView.addObject("message", message);return modelAndView;}}
几乎所有方法和请求映射都是清楚的。 但我想强调指出, editTeamPage()和edditingTeam()方法的@RequestMapping包含方法属性的不同值。 现在是时候查看这些映射的JSP了:
“添加新团队”页面:
...
<h1>Add team page</h1>
<p>Here you can add a new team.</p>
<form:form method="POST" commandname="team" action="${pageContext.request.contextPath}/team/add/process.html">
<table>
<tbody><tr><td>Name:</td><td><form:input path="name"></form:input></td></tr><tr><td>Rating:</td><td><form:input path="rating"></form:input></td></tr><tr><td><input value="Add" type="submit"></td><td></td></tr>
</tbody>
</table>
</form:form><p><a href="${pageContext.request.contextPath}/index.html">Home page</a></p>
...
“球队名单”页面:
...
<h1>List of teams</h1>
<p>Here you can see the list of the teams, edit them, remove or update.</p>
<c:foreach var="team" items="${teams}">
</c:foreach><table border="1px" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th width="10%">id</th><th width="15%">name</th><th width="10%">rating</th><th width="10%">actions</th>
</tr>
</thead>
<tbody>
<tr><td>${team.id}</td><td>${team.name}</td><td>${team.rating}</td><td><a href="${pageContext.request.contextPath}/team/edit/${team.id}.html">Edit</a><br><a href="${pageContext.request.contextPath}/team/delete/${team.id}.html">Delete</a><br></td>
</tr></tbody>
</table><p><a href="${pageContext.request.contextPath}/index.html">Home page</a></p>
...
“编辑团队”页面:
...
<h1>Edit team page</h1>
<p>Here you can edit the existing team.</p>
<p>${message}</p>
<form:form method="POST" commandname="team" action="${pageContext.request.contextPath}/team/edit/${team.id}.html">
<table>
<tbody><tr><td>Name:</td><td><form:input path="name"></form:input></td></tr><tr><td>Rating:</td><td><form:input path="rating"></form:input></td></tr><tr><td><input value="Edit" type="submit"></td><td></td></tr>
</tbody>
</table>
</form:form><p><a href="${pageContext.request.contextPath}/index.html">Home page</a></p>
...
以及“团队名单”页面的屏幕截图:
摘要
集成多种技术通常不是一件容易的事,因此要耐心地取得成功。 帖子中没有很多资源,因此您可以访问我的GitHub来探索您感兴趣的类。
翻译自: https://www.javacodegeeks.com/2013/04/spring-mvc-hibernate-maven-crud-operations-example.html