Hibernate专题

Spring MVC + Hibernate + Maven: CRUD增删改查教程源码

  Spring MVC + Hibernate + Maven: CRUD增删改查教程源码下载

目标:创建示例Web应用程序,基于Spring MVC HibernateMaven。用户界面接口将是基于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
       @GeneratedValue
       private 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;
       }

}

 

有关配置的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";

       @Resource
       private Environment env;

       @Bean
       public 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;
       }

       @Bean
       public 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; 
       }

       @Bean
       public HibernateTransactionManager transactionManager() {
              HibernateTransactionManager transactionManager = new HibernateTransactionManager();
              transactionManager.setSessionFactory(sessionFactory().getObject());
              return transactionManager;
       }

       @Bean
       public UrlBasedViewResolver setupViewResolver() {
              UrlBasedViewResolver resolver = new UrlBasedViewResolver();
              resolver.setPrefix("/WEB-INF/pages/");
              resolver.setSuffix(".jsp");
              resolver.setViewClass(JstlView.class);
              return resolver;
       }

}

数据库连接参数:修改成你的数据库连接密码用户名

#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接口和实现:

public interface TeamDAO {

       public void addTeam(Team team);
       public void updateTeam(Team team);
       public Team getTeam(int id);
       public void deleteTeam(int id);
       public List

          getTeams();

}@Repository
public class TeamDAOImpl implements TeamDAO {

       @Autowired
       private 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 List

          getTeams() {
              return getCurrentSession().createQuery("from Team").list();
       }

}

服务接口和实现:

public interface TeamService {

       public void addTeam(Team team);
       public void updateTeam(Team team);
       public Team getTeam(int id);
       public void deleteTeam(int id);
       public List

          getTeams();

}
@Service
@Transactional
public class TeamServiceImpl implements TeamService {

       @Autowired
       private 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 List

          getTeams() {
              return teamDAO.getTeams();
       }

}

控制器和页面:

@Controller
public class LinkController {

       @RequestMapping(value="/")
       public ModelAndView mainPage() {
              return new ModelAndView("home");
       }

       @RequestMapping(value="/index")
       public ModelAndView indexPage() {
              return new ModelAndView("home");
       }

}
...
<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 {

       @Autowired
       private 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");

              List

          teams = 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;
       }

}

新增页面:

...
<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>
...

列出所有teams页面:

...
<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>
...

效果图:

 

Spring Data JPA 实现简单的CRUD增删改查源码案例

Spring JPA Data + Hibernate + MySQL + Maven教程源码

猜你喜欢