Spring-Boot初体验

来源:互联网 发布:大商创开源破解版源码 编辑:程序博客网 时间:2024/05/17 13:40
@ReuqestMapping         URL映射,处理请求(以集合方式可添加多个请求名;也可以在类上边使用为其指定一个URL

@Controller            处理http请求,标记类将其变为spring对象,用于标注控制层组件(如struts中的action)

@Repository            持久层组件,用于标注数据访问组件,即DAO组件
    
@Component            泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

@RequestParam            获取传递参数的值

    //value:获取的参数;required:是否必传(绑定);default:默认值(String型);myId:将取下的id的值赋给myId

    public String say(@RequestParam(value = "id",required = false,default = "0") Integer myId)
    {
        return "id:" + myId;
    }


@PathVariable            获取URL中的值

@GetMapping(value = "/say")    等于@ReuqestMapping (value = "/say",method = RequestMethod.GET)




数据库操作:
@Entity                表示此类就是数据库中的一个表(创建一个类,会自动根据类中属性添加表)

@Id                表属性

@GenerateValue            Id自增


yml中:(格式很重要,不能删空格)
spring:
  profilea:
    active: dev  //yml文件后缀
  datasource:
    drive-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/databasename
    username: root
    password: root
  jpa:            //通过jpa不需要sql语句就可以实现数据库操作
    hibernate:
      ddl-auto: create //每次运行都会创建空表,如果数据库中有则会将其删掉
      ddl-auto: update //创建表,若之前表中存在数据则会保留(常用)
    shoe-sql: true     //控制台打印sql语句

//创建GirlRepository接口(文件类型为interface),继承Jpa库(小提示:extends 语句可以使用一个接口继承多个接口,通

过 implements 语句可以使用一个类继承多个接口。

public interface GirlRepository extends JpaRepository<Girl, Integer>{
        //什么也不用写
}





//get方法添加girl信息(需创建Entity类及getter/setter方法,以及配置yml有关属性)
@GetMapping(value = "/girl")
public Girl girlAdd(@RequestParam("cupSize") String cupSize,
            @RequestParam("age") Integer age){
    Girl girl = new Girl();
    girl.setCupSize(cupSize);
    girl.setAge(age);

    return girlRepository.save(girl); //调用girlRepository中的save借口,返回值为对象
}
//put方法更新girl信息
@PutMapping(value = "/girl/{id}")   //使用put的时候要用postman里边的x-www
public Girl girlUpdate(@PathVariable("id") Integer id,
               @Requestparam("cupSize") String cupSize,
               @RequestParam("age") Integer age){
    Girl girl = new Girl();
    girl.setId(id);
    girl.setCupSize(cupSize);
    girl.setAge(age);

    return girlRepository.save(girl);    
}

@Transactional            同时操作多条数据时,若有一条执行不了,其他均不执行(写在方法上方)

原创粉丝点击