1.创建项目的时候要勾选好mybatis
?2. 创建mapper/ProviderMapper
package com.cc.springboot.mapper;
import com.cc.springboot.entities.Provider;
import org.apache.ibatis.annotations.*;
//使用mybatis注解版本
@Mapper //指定这是操作数据的mapper
public interface ProviderMapper {
// 查询某一项
@Select("select * from provider where pid=#{pid}")
Provider getProviderByPid(Integer pid);
// 插入
// useGeneratedKeys 是否使用自增主键,keyProperty指定实体类中的那个属性封装主键值
@Options(useGeneratedKeys = true,keyProperty = "pid")
@Insert("insert into provider(providerName) values (#{providerName})")
int addProvider(Provider provider);
// 删除
@Delete("delete from provider where pid=#{pid}")
int deleteProvider(Integer pid);
// 更新
@Update("update provider set providerName=#{providerName} where pid=#{pid}")
int updateProvider(Provider provider);
}
知识点:1.数据库的操作
? ? ? ? ? ? ? ?2.插入时封装主键值,回显pid,没有的话,你回显的provider中pid显示null
3.controller/ProviderController使用
package com.cc.springboot.controller;
import com.cc.springboot.entities.Provider;
import com.cc.springboot.mapper.ProviderMapper;
import org.apache.ibatis.annotations.Options;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProviderController {
@Autowired
ProviderMapper providerMapper;
@GetMapping("/provider/{pid}")
public Provider getProvider(@PathVariable("pid") Integer pid){
Provider provider = providerMapper.getProviderByPid(pid);
return provider;
}
@GetMapping("/provider")
public Provider insertProvider(Provider provider){
providerMapper.addProvider(provider);
return provider;
}
}
? 知识点? @RestController
4.数据库中是'-',实体类中是驼峰命名,导致显示不出相关数据
?config/MyBatisConfig
package com.cc.springboot.config;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//mybatis的注解版本相关配置
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer(){
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
// 开启驼峰命名方式
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
5.运行的应用程序
package com.cc.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//会自动装配指定包下面所有Mapper,省的在每个Mapper上面写@Mapper
@MapperScan("com.cc.springboot.mapper")
@SpringBootApplication
public class Springboot08DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot08DataMybatisApplication.class, args);
}
}
//会自动装配指定包下面所有Mapper,省的在每个Mapper上面写@Mapper
@MapperScan("com.cc.springboot.mapper")
|