spring-boot 学习笔记(2)

来源:互联网 发布:软件需求分析方法 编辑:程序博客网 时间:2024/06/14 13:36

一 Controller的使用

  1. @Controller 处理http请求,必须配合模版使用,在pom文件中加入依赖
    <dependency>
        <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
    </dependency>
  2. @RestController Spring4之后新加的注解,原来返回json需要
    @ResponseBody配合@Controller
  3. @RequestMapping 配置url映射,设置访问方法的url,该注解也可以放到类上,作为整个类的访问请求,

  4. 需要两个url访问同一个方法,在RequestMapping的value={“/hello”,”/hi”}

  5. 获取参数方法
    a. @RequestMapping(value=”/say/{id}”) 获得url中的参数
    public String method( @PathVariable(“id”)Integer id)
    b. 传统url: /hello/say?id=100 获得id的方法
    public String method(@RequestParam(“id”,defaultValue=”0”) Integer myid)
    c. GetMapping 组合注解
    @GetMapping(value=“/hello”) PostMapping() PutMapping DeleteMapping

二 数据库操作

  1. Spring-Data-Jpa定义一系列对象持久化的标准,实现该规范的产品有Hibernate,TopLink
  2. 使用数据库需要添加两个组件在pom文件中
    a. <artifactId>spring-boot-starter-test</artifactId>
    <artifactId>mysql-connector-java</artifactId>
    b. application.yml:
    datasouce:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql:127.0.0.1:3306/dbgirl(数据库名字)
        username: root
        password: 123456
    jpa:
        hibernate:
        ddl-auto:create(每次跑创建新的表,数据会不见)
    update(更新,数据仍然存在)
    show-sql: true
  3. 数据库表的创建方法:
    a. 建立实体类,加注解@Entity ,表示该类与数据库的表一一对应
    b. @Id
    @GeneratedValue(自增)
    private Integer id
    无参的构造函数和所有属性的get/set方法
  4. spring-jpa数据操作
    a. 新建一个接口
    public interface GirlRepository extends JpaRepository<数据库
    表名,id的类型Integer>
    b. 在另一个类中使用GirlRepository
    @Autowired
    private GirlRepository girlRepository
    girlRepository.findAll()返回某个数据库的全部数据
    girlRepository.save(girl)新建或更新数据库
    girlRepository.findOne(id)查询某个女生
    girlRepository.delete(id) 删除某个女生
    注意:在使用put请求时,数据格式要改成x-www-form-urlencoded
  5. 条件查找,扩展GirlRepository接口 findByAge(Integer age)

三 数据库的事务管理

  1. 在方法中加入@Transactional注解,只要该方法出现错误,整个结果回到原来
原创粉丝点击