1.新建springboot项目
(1).可以在 spring项目搭建网站上去生成项目,如下图所示,可以选择maven版本跟gradle版本,输入项目名Group跟Artifact,点击generate Project 即可创建对应的springboot项目
(2).可以在idea上点击new,点击spring initializr,进入面板后就跟上面一样,输入,创建。
2.查看入口类application,也就是springBoot的启动类。
@SpringBootApplication
public class FirstAppDemoApplication {
public static void main(String[] args) {
SpringApplication.run(FirstAppDemoApplication.class, args);
}
}
可以点击@SpringBootAppication注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
除了前四个元注解以外,我们可以发现@SpringBootApplication注解中包含了@SpringBootCOnfiguration,@EnableAutoConfiguration以及常用的@ComponentScan注解
- SpringBootCOnfiguration,就是springmvc里面的Configuration注解,告诉Spring容器,这是一个配置类。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}
- EnableAutoConfiguration ,包含AutoConfigurationPackage和Import注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
- AutoConfigurationPackage中只有一个@Import注解,也就是导入一个Registrar注册类,Registrar的源码中大致意思应该是帮助spring容器注册包类的信息
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}
Registrar的注册代码如下
AutoConfigurationPackages.register(registry, (new AutoConfigurationPackages.PackageImport(metadata)).getPackageName());
- Import中导入的是我们在配置springcontext中的自动配置选择器,这里不详细说了,有兴趣的同学可以自己看下源码
- ComponentScan就是我们通常使用的组件扫描,这里是告诉spring,我们需要spring对我们自己自定义的过滤器跟排除过滤器进行扫描。因此,我们如果需要定义过滤器跟排除过滤器 ,则必须继承AutoConfigurationExcludeFilter跟TypeExcludeFilter类。
3.springBoot继承mybatis
1.在pom.xml中添加mybatis依赖
<dependency>
<groupId>mysql</groupId>
<artifactId> mysql-connector-java</artifactId>
<version> 5.1.30</version>
</dependency>
2.在application.properties中添加数据源的配置以及mysql的配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
mybatis.mapper-locations=classpath:/mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
3.编写dao层:
public interface UserReposity{
@Select("select * from user")
List<User> findAll(User user);
}
@Select注解并不能满足我们日常开发所需要的动态sql,因此,在这里可以使用@SelectProvider注解来进行动态sql的生成。
@SelectProvider(type = UserDynaSql.class,method = "selectProvider")
List<User> selectProvider(User user);
UserDynaSql类的代码如下所示:
package com.gc.firstappdemo.mybatis;
import com.gc.firstappdemo.domain.User;
import org.apache.ibatis.jdbc.SQL;
public class UserDynaSql {
public String selectProvider(User user){
return new SQL(){
{
SELECT("*");
FROM("user");
if(user.getUserName() != null){
WHERE("user_name = #{userName}");
}
}
}.toString();
}
public String insertProvider(User user){
return new SQL(){
{
INSERT_INTO("user");
if(user.getUserName() != null){
VALUES("user_name","#{userName}");
}
if(user.getUserId() != null){
VALUES("user_id","#{userId}");
}
}
}.toString();
}
}
对应selectProdiver注解的还有其他增删改注解InsertProvider,UpdateProvider,DeleteProvier,用法都跟查询的注解一样。SQL继承的抽象类代码中,大家可以自己去看下。
4.在主程序中加入mapper扫描,告诉springBoot去扫描这个目录下所有的Mapper接口
@MapperScan("com.gc.firstappdemo.reposity")
数据组装
当不同表之间的数据存在一对多或者多对多的时候,我们需要对查询出来的数据进行组装。
在之前的springmvc继承mybatis中,这种工作是在mybatis映射的xml文件里面去做的,代码类似下面所示(property,column映射的是对象属性名跟表名):
<resultMap id="workDetail" type="Work">
<id property="id" column="id" />
<result property="studentName" column="studentName"/>
<result property="headImgUrl" column="headImgUrl"/>
<result property="schoolName" column="schoolName"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
<result property="type" column="type"/>
<result property="idNum" column="idNum"/>
<collection property="workAttList" ofType="WorkAtt">
<result property="originalImageUrl" column="originalImageUrl"/>
</collection>
</resultMap>
springBoot提供了@Results注解,可以对查询出来的结果进行组装。
@Select("select * from user")
@Results({
@Result(id=true,column = "user_Id",property = "userId"),
@Result(column = "user_Name",property = "userName"),
@Result(column = "user_Password",property = "userPassword"),
@Result(column = "user_id",property = "roles",
many = @Many(select = "com.gc.firstappdemo.reposity.RoleReposity.listByUserId",
fetchType = FetchType.EAGER)),})
List<UserDto> findUserDtoAll(User user);
listByUserId的查询:
@Select("select r.* from role r\n" +
"join user_role ur on r.id = ur.role_id\n" +
"join users u on u.user_id = ur.user_id\n" +
"where u.user_id = #{userId}")
List<Role> listByUserId(String userId);
userId这个参数是通过column中的“user_Id”传过去的。(如果这边没有查到roles里面的数据,可以查看mybatis.configuration.map-underscore-to-camel-case=true这个配置有没有加,这个配置是让mybatis自动转换驼峰命名法)
4.springBoot集成spring-data-jpa
pom中添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
1.配置数据源,在application.properties配置中加入:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
mybatis.mapper-locations=classpath:/mapper/*.xml
mybatis.configuration.map-underscore-to-camel-case=true
spring.jpa.database=MYSQL
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
server.port=8080
2.在实体类中添加注解
- @Entity注解表明该类为实体类或者表
@Entity
public class User {
- @Id注解表示该字段为表的主键,@GeneratedValue表示生成主键的方式
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String userId;
- @ManyToMany注解是用来映射该表(实体)与其他表(实体)多对多的关系,@JoinTable用来处理连接多对多关系映射,name字段为多对多关系的中间表
jointColumns里面添加的是,中间表对应该实体(User)的主键;这个就相当于left joint user_roles on User.id = user_roles.user_id 中的对应关系
inverseJoinColumns里面添加的是,中间表对应于映射表(Role)的主键;相当于left joint role on role.id = user_roles.role_id 中的对应关系
@ManyToMany(
targetEntity = Role.class,
cascade = {CascadeType.PERSIST},
fetch = FetchType.EAGER
)
@JoinTable(
name = "user_role",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "role_id")}
)
private Set<Role> roleSet;
3.dao层继承JpaRepository
public interface UserReposity2 extends JpaRepository<User,String> {}
@DynamicInsert,@DynamicUpdate可以直接实现mybatis中动态sql。