真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

基于springboot1.5.4集成jpa+hibernate+jdbcTemplate(詳解)

1.pom添加依賴

創(chuàng)新互聯(lián)公司長期為成百上千客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為石鼓企業(yè)提供專業(yè)的成都做網(wǎng)站、網(wǎng)站制作,石鼓網(wǎng)站改版等技術(shù)服務(wù)。擁有十載豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。


     
      org.springframework.boot
      spring-boot-starter-data-jpa
    
    
      MySQL
      mysql-connector-java
      5.1.42
    

2.添加數(shù)據(jù)源配置(DataSource啥的,一系列對象spring boot 都會給你注入的,配置配置即可!)

spring.datasource.url=jdbc:mysql://localhost/test?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#database pool config
# Number of ms to wait before throwing an exception if no connection is available.
spring.datasource.tomcat.max-wait=10000
# Maximum number of active connections that can be allocated from this pool at the same time.
spring.datasource.tomcat.max-active=300
# Validate the connection before borrowing it from the pool.
spring.datasource.tomcat.test-on-borrow=true
# initial pool size
spring.datasource.tomcat.initial-size=20


#=====================jpa config================================
#實體類維護(hù)數(shù)據(jù)庫表結(jié)構(gòu)的具體行為:update/create/create-drop/validate/none
spring.jpa.hibernate.ddl-auto=none
#打印sql語句
spring.jpa.show-sql=true
#格式化輸出的json字符串
spring.jackson.serialization.indent_output=true

3.新建實體

@Entity
@Table(name="user")
public class User {

  @Id
  @Column(name="id")
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  @Column(name="number")
  private String number;

  @Column(name="name")
  private String name;

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public String getNumber() {
    return number;
  }

  public void setNumber(String number) {
    this.number = number;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

4.dao層

public interface UserDao{

  User getById(int id);

  User getByNumber(String number);

  int addUser(User user);

  void deleteUserById(int id);

  User updateUser(User user);

}
@Repository
public class UserDaoImpl implements UserDao {

  @PersistenceContext
  private EntityManager entityManager;

  @Override
  public User getById(int id) {
    //find by primary key
    return this.entityManager.find(User.class,id);
  }

  @Override
  public User getByNumber(String number) {
    Query query = this.entityManager.createQuery("from User u where u.number=:number",User.class);
    query.setParameter("number",number);
    User user = (User)query.getSingleResult();
    return user;
  }

  @Override
  public int addUser(User user) {
    this.entityManager.persist(user);
    //print the id
    System.out.println(user.getId());
    return user.getId();
  }

  @Override
  public void deleteUserById(int id) {
    User user = this.entityManager.find(User.class,id); //關(guān)聯(lián)到記錄,方可刪除
    this.entityManager.remove(user);
  }

  @Override
  public User updateUser(User user) {
    User userNew = this.entityManager.merge(user);
    return userNew;
  }
}

5.service層

public interface UserService {

  User getById(int id);

  User getByNumber(String number);

  int addUser(User user,boolean throwEx);

  void deleteUserById(int id);

  User updateUser(User user);
}
@Service
@Transactional
public class UserServiceImpl implements UserService {

  @Autowired
  private UserDao userDao;

  @Override
  @Transactional(readOnly = true)
  public User getById(int id) {
    return userDao.getById(id);
  }

  @Override
  @Transactional(readOnly = true)
  public User getByNumber(String number) {
    return userDao.getByNumber(number);
  }

  @Override
  public int addUser(User user,boolean throwEx) {
    int id= this.userDao.addUser(user);
    if(throwEx){
      throw new RuntimeException("throw a ex");
    }
    return id;
  }

  @Override
  public void deleteUserById(int id) {
    this.userDao.deleteUserById(id);
  }

  @Override
  public User updateUser(User user) {
    return this.userDao.updateUser(user);
  }


}

6.controller層

@Controller("user1")
@RequestMapping("/jpa/user")
public class UserController {
  /**
   * 日志(slf4j->logback)
   */
  private static final Logger logger = LoggerFactory.getLogger(UserController.class);

  @Autowired
  private UserService userService;

  /**
   * 返回text格式數(shù)據(jù)
   * @param id 主鍵id
   * @return 用戶json字符串
   */
  @RequestMapping("/get/id/{id}")
  @ResponseBody
  public String getUserById(@PathVariable("id")String id){
    logger.info("request /user/get/id/{id}, parameter is "+id);
    User user = userService.getById(Integer.parseInt(id));
    return JSONObject.toJSONString(user);
  }

  /**
   * 返回json格式數(shù)據(jù)
   * @param number 編號
   * @return 用戶
   */
  @RequestMapping("/get/number/{number}")
  @ResponseBody
  public User getUserByNumber(@PathVariable("number")String number){
    User user = userService.getByNumber(number);
    return user;
  }

  @RequestMapping("/add/{number}/{name}")
  @ResponseBody
  public String addUser(@PathVariable("number")String number,@PathVariable("name")String name,boolean throwEx){
    User user = new User();
    user.setNumber(number);
    user.setName(name);
    int id = -1;
    try{
      id = userService.addUser(user,throwEx);
    }catch (RuntimeException ex){
      System.out.println(ex.getMessage());
    }
    return String.valueOf(id);
  }

  @RequestMapping("/delete/{id}")
  @ResponseBody
  public void getUserById(@PathVariable("id")int id){
    this.userService.deleteUserById(id);
  }

  @RequestMapping("/update/{id}/{number}/{name}")
  @ResponseBody
  public User addUser(@PathVariable("id")int id, @PathVariable("number")String number, @PathVariable("name")String name){
    User user = new User();
    user.setId(id);
    user.setNumber(number);
    user.setName(name);
    return userService.updateUser(user);
  }
}

7. spring data jpa新使用方式,更高級

1.dao

@Repository
public interface UserRepository extends JpaRepository {
  /**
   * spring data jpa 會自動注入實現(xiàn)(根據(jù)方法命名規(guī)范)
   * @return
   */
  User findByNumber(String number);


  @Modifying
  @Query("delete from User u where u.id = :id")
  void deleteUser(@Param("id")int id);
}

2.service

public interface UserService {

  User findById(int id);

  User findByNumber(String number);

  List findAllUserByPage(int page,int size);

  User updateUser(User user,boolean throwEx);

  void deleteUser(int id);
}

@Service
@Transactional
public class UserServiceImpl implements UserService {

  @Autowired
  private UserRepository userRepository;

  @Override
  public User findById(int id) {
    return this.userRepository.findOne(id);
  }

  @Override
  public User findByNumber(String number) {
    return this.userRepository.findByNumber(number);
  }

  @Override
  public List findAllUserByPage(int page,int size) {
    Pageable pageable = new PageRequest(page, size);
    Page users = this.userRepository.findAll(pageable);
    return users.getContent();
  }

  @Override
  public User updateUser(User user,boolean throwEx) {
    User userNew = this.userRepository.save(user);
    if(throwEx){
      throw new RuntimeException("throw a ex");
    }
    return userNew;
  }

  @Override
  public void deleteUser(int id) {
    this.userRepository.deleteUser(id);
  }
}


3.controller

@Controller("user2")
@RequestMapping("/datajpa/user")
public class UserController {
  /**
   * 日志(slf4j->logback)
   */
  private static final Logger logger = LoggerFactory.getLogger(UserController.class);

  @Autowired
  private UserService userService;

  /**
   * 返回text格式數(shù)據(jù)
   * @param id 主鍵id
   * @return 用戶json字符串
   */
  @RequestMapping("/get/id/{id}")
  @ResponseBody
  public String getUserById(@PathVariable("id")String id){
    logger.info("request /user/get/id/{id}, parameter is "+id);
    User user = userService.findById(Integer.parseInt(id));
    return JSONObject.toJSONString(user);
  }

  /**
   * 返回json格式數(shù)據(jù)
   * @param number 編號
   * @return 用戶
   */
  @RequestMapping("/get/number/{number}")
  @ResponseBody
  public User getUserByNumber(@PathVariable("number")String number){
    User user = userService.findByNumber(number);
    return user;
  }

  @RequestMapping("/get/all/{page}/{size}")
  @ResponseBody
  public List getAllUserByPage(@PathVariable("page")int page,@PathVariable("size")int size){
    return this.userService.findAllUserByPage(page,size);
  }

  @RequestMapping("/update/{id}/{number}/{name}")
  @ResponseBody
  public User addUser(@PathVariable("id")int id, @PathVariable("number")String number, @PathVariable("name")String name,boolean throwEx){
    User user = new User();
    user.setId(id);
    user.setNumber(number);
    user.setName(name);
    User userNew = null;
    try{
      userService.updateUser(user,throwEx);
    }catch (RuntimeException ex){
      System.out.println(ex.getMessage());
    }
    return userNew;
  }

  @RequestMapping("/delete/{id}")
  @ResponseBody
  public void getUserById(@PathVariable("id")int id){
    this.userService.deleteUser(id);
  }


}

8.注入jdbcTemplate和transactionTemplate,使用傳統(tǒng)方式操作數(shù)據(jù)庫,更加靈活,方法如下

@Autowired
  private JdbcTemplate jdbcTemplate;

  @Autowired
  private TransactionTemplate transactionTemplate;

  /**
   * 手動控制事物測試
   * @param throwEx
   */
  @Override
  public void testTransactionManually(boolean throwEx) {

    try {
      transactionTemplate.execute(new TransactionCallback() {

        /**
         * 事物代碼
         *
         * @param transactionStatus 事物狀態(tài)
         * @return 是否成功
         */
        @Override
        public Boolean doInTransaction(TransactionStatus transactionStatus) {
          User user = new User();
          user.setId(1);
          int a = new Random().nextInt(10); //0-9
          user.setNumber("10000u" + a);
          jdbcTemplate.update("UPDATE USER SET NUMBER=? WHERE ID=?", new Object[]{user.getNumber(), user.getId()}, new int[]{Types.VARCHAR, Types.INTEGER});
          if (throwEx) {
            throw new RuntimeException("try throw exception"); //看看會不會回滾
          }
          return true;
        }
      });
    }catch (RuntimeException ex){
      System.out.println(ex.getMessage());
    }

  }

  /**
   * 手動執(zhí)行jdbc測試
   */
  @Override
  public void testJdbcTemplate() {
    User user = new User();
    int a = new Random().nextInt(10); //0-9
    user.setNumber("10000i"+ a );
    user.setName("name"+a);
    this.jdbcTemplate.update("INSERT into USER(NUMBER,NAME )VALUES (?,?)",user.getNumber(),user.getName());
  }

至此,我已經(jīng)講了三種方式(jpa兩種+jdbcTemplate)如何操作數(shù)據(jù)庫了,你愛怎么用就怎么用,上述代碼均是實踐證明可行的!

以上這篇基于spring boot 1.5.4 集成 jpa+hibernate+jdbcTemplate(詳解)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持創(chuàng)新互聯(lián)。


網(wǎng)頁標(biāo)題:基于springboot1.5.4集成jpa+hibernate+jdbcTemplate(詳解)
標(biāo)題網(wǎng)址:http://weahome.cn/article/gochgc.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部