通过阅读本文之后,你将学会使用在几分钟内搭建好一个拥有基本功能的web后台开发框架。
一:使用idea创建spring boot应用
1.使用idea创建一个project,选择Spring Initializr选项,选择和团队一致的jdk版本之后next。
2.输入项目的包名
3.在依赖选项卡上勾选上Web即可
4.选择项目代码存放路径
5.最后你会看到下面这个样子的项目文件,等待idea加载完所需要的依赖即可。
二:配合使用JPA实现增删查改
1.为了更好的代码管理,做以下分层,并且注意:所有的代码都是和SpringBootDemoApplication在同一个文件夹下的,这点需要注意一下,如果不是在同一个文件夹下的话会报错。
2.在数据库中新建一张表:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for boss
-- ----------------------------
DROP TABLE IF EXISTS `boss`;
CREATE TABLE `boss` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
3.创建repository文件夹下,新建BossRepository类。(使用的是JPA)
package com.example.springbootdemo.repository;
import com.example.springbootdemo.model.Boss;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Repository
public interface BossRepository extends JpaRepository<Boss, Long> {
@Transactional
@Modifying(clearAutomatically = true)
@Query(value ="UPDATE boss SET name=?2 WHERE id =?1 ",nativeQuery = true)
Integer update(Long id,String name);
@Transactional
@Modifying(clearAutomatically = true)
@Query(value ="DELETE from boss WHERE id =?1 ",nativeQuery = true)
void deleteById(Long id);
Page<Boss> findAll(Pageable pageable);
List<Boss> findBossByNameLike(String name);
@Query(value ="select * from boss WHERE id =?1 ",nativeQuery = true)
Boss queryById(Long id);
}
4.在service文件夹下,新建BossService类:
package com.example.springbootdemo.service;
import com.example.springbootdemo.mapper.Boss2Mapper;
import com.example.springbootdemo.mapper.BossMapper;
import com.example.springbootdemo.model.Boss;
import com.example.springbootdemo.repository.BossRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import static com.github.pagehelper.page.PageMethod.startPage;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class BossService {
@Autowired
private BossRepository bossRepository;
public List<Boss> findAll(){
return bossRepository.findAll();
}
/**
* @描述: 分页查询
* @作者 YangZhiRan
* @时间 2018/6/7 23:0