springboot 注册dao层 service 层

可以使用三种注解来引入DAO层的接口到spring容器中。
1.@Mapper,写在每一个DAO层接口上,如下:

2.@MapperScan和@ComponentScan两者之一。前者的意义是将指定包中的所有接口都标注为DAO层接口,相当于在每一个接口上写@Mapper。后者则是代替所有

//指定这是一个操作数据库的mapper
@Mapper
public
interface DepartmentMapper { @Select("select * from department where id=#{id}") public Department getDeptById(Integer id); @Delete("delete from department where id=#{id}") public int deleteDeptById(Integer id); @Options(useGeneratedKeys = true,keyProperty = "id") @Insert("insert into department(departmentName) values(#{departmentName})") public int insertDept(Department department); @Update("update department set departmentName=#{departmentName} where id=#{id}") public int updateDept(Department department); }
使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}

第二种

配置文件版

mybatis:
config‐location: classpath:mybatis/mybatis‐config.xml 指定全局配置文件的位置
mapper‐locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置

自定义MyBatis的配置规则;给容器中添加一个ConfigurationCustomizer;

给下列文件设置驼峰命名法
@org.springframework.context.annotation.Configuration
public class MyBatisConfig { @Bean public ConfigurationCustomizer configurationCustomizer(){ return new ConfigurationCustomizer(){ @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } }

整合SpringData JPA

SpringData简介

JPA:ORM(Object Relational Mapping);
1)、编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;

//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class User {
@Id //这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
private Integer id;
@Column(name = "last_name",length = 50) //这是和数据表对应的一个列
private String lastName;
@Column //省略默认列名就是属性名
private String email;

编写一个Dao接口来操作实体类对应的数据表(Repository)

猜你喜欢

转载自www.cnblogs.com/zhulina-917/p/10502890.html
今日推荐