Hibernate专题

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

  Spring JPA Data + Hibernate + MySQL + Maven源码下载

涉及三个步骤:

创建mysql数据库

CREATE TABLE `shops` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `employees_number` int(6) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

其相应的实体失血模型:

@Entity
@Table(name = "shops")
public class Shop {

       @Id
       @GeneratedValue
       private Integer id;

       private String name;

       @Column(name = "employees_number")
       private Integer emplNumber;

       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 getEmplNumber() {
              return emplNumber;
       }

       public void setEmplNumber(Integer emplNumber) {
              this.emplNumber = emplNumber;
       }
}

项目目录结构:

配置属性中配置一下数据库参数:

#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.spr.model

 

WebAppconfig包含了所有Java的配置:

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.spr")
@PropertySource("classpath:application.properties")
@EnableJpaRepositories("com.spr.repository")
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 LocalContainerEntityManagerFactoryBean entityManagerFactory() {
              LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
              entityManagerFactoryBean.setDataSource(dataSource());
              entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistence.class);
              entityManagerFactoryBean.setPackagesToScan(env.
getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));

              entityManagerFactoryBean.setJpaProperties(hibProperties());

              return entityManagerFactoryBean;
       }

       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 JpaTransactionManager transactionManager() {
              JpaTransactionManager transactionManager = new JpaTransactionManager();
              transactionManager.setEntityManagerFactory(entityManagerFactory().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;
       }

}

注意  @EnableJpaRepositories, 它激活使用JPA仓库。将扫描com.spr.repository检测库。在EntityManagerFactory中使用Hibernate将被用来作为JPA实现。

DAO & Service layers

shop的仓储:

package com.spr.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.spr.model.Shop;

public interface ShopRepository extends JpaRepository<shop, integer=""> {

}

JpaRepository接口可以包含任何实体(CRUD操作)

下面是服务接口:

public interface ShopService {

       public Shop create(Shop shop);
       public Shop delete(int id) throws ShopNotFound;
       public List findAll();
       public Shop update(Shop shop) throws ShopNotFound;
       public Shop findById(int id);

}

服务实现:

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spr.exception.ShopNotFound;
import com.spr.model.Shop;
import com.spr.repository.ShopRepository;

@Service
public class ShopServiceImpl implements ShopService {

       @Resource
       private ShopRepository shopRepository;

       @Override
       @Transactional
       public Shop create(Shop shop) {
              Shop createdShop = shop;
              return shopRepository.save(createdShop);
       }

       @Override
       @Transactional
       public Shop findById(int id) {
              return shopRepository.findOne(id);
       }

       @Override
       @Transactional(rollbackFor=ShopNotFound.class)
       public Shop delete(int id) throws ShopNotFound {
              Shop deletedShop = shopRepository.findOne(id);

              if (deletedShop == null)
                     throw new ShopNotFound();

              shopRepository.delete(deletedShop);
              return deletedShop;
       }

       @Override
       @Transactional
       public List findAll() {
              return shopRepository.findAll();
       }

       @Override
       @Transactional(rollbackFor=ShopNotFound.class)
       public Shop update(Shop shop) throws ShopNotFound {
              Shop updatedShop = shopRepository.findOne(shop.getId());

              if (updatedShop == null)
                     throw new ShopNotFound();

              updatedShop.setName(shop.getName());
              updatedShop.setEmplNumber(shop.getEmplNumber());
              return updatedShop;
       }

}

Controller

@Controller
@RequestMapping(value="/shop")
public class ShopController {

       @Autowired
       private ShopService shopService;

       @RequestMapping(value="/create", method=RequestMethod.GET)
       public ModelAndView newShopPage() {
              ModelAndView mav = new ModelAndView("shop-new", "shop", new Shop());
              return mav;
       }

       @RequestMapping(value="/create", method=RequestMethod.POST)
       public ModelAndView createNewShop(@ModelAttribute Shop shop,
                     final RedirectAttributes redirectAttributes) {

              ModelAndView mav = new ModelAndView();
              String message = "New shop "+shop.getName()+" was successfully created.";

              shopService.create(shop);
              mav.setViewName("redirect:/index.html");

              redirectAttributes.addFlashAttribute("message", message);   
              return mav;         
       }

       @RequestMapping(value="/list", method=RequestMethod.GET)
       public ModelAndView shopListPage() {
              ModelAndView mav = new ModelAndView("shop-list");
              List shopList = shopService.findAll();
              mav.addObject("shopList", shopList);
              return mav;
       }

       @RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
       public ModelAndView editShopPage(@PathVariable Integer id) {
              ModelAndView mav = new ModelAndView("shop-edit");
              Shop shop = shopService.findById(id);
              mav.addObject("shop", shop);
              return mav;
       }

       @RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
       public ModelAndView editShop(@ModelAttribute Shop shop,
                     @PathVariable Integer id,
                     final RedirectAttributes redirectAttributes) throws ShopNotFound {

              ModelAndView mav = new ModelAndView("redirect:/index.html");
              String message = "Shop was successfully updated.";

              shopService.update(shop);

              redirectAttributes.addFlashAttribute("message", message);   
              return mav;
       }

       @RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
       public ModelAndView deleteShop(@PathVariable Integer id,
                     final RedirectAttributes redirectAttributes) throws ShopNotFound {

              ModelAndView mav = new ModelAndView("redirect:/index.html");          

              Shop shop = shopService.delete(id);
              String message = "The shop "+shop.getName()+" was successfully deleted.";

              redirectAttributes.addFlashAttribute("message", message);
              return mav;
       }

}

其中有CRUD增删改查的操作,运行显示结果如下:

 

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

猜你喜欢