1.1新建项目
选择Spring Initializr或者maven项目都可以
初始化好的项目
1.2 引pom
完全可以和java项目中引入依赖画等号
引入SQLServer的驱动包 还有我们要来操作数据库的Mybatis -plus
<!--lombok用来简化实体类:需要安装lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--for SqlServer-->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
1.3 改yml
spring:
datasource:
driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
url: jdbc:sqlserver://localhost:1433;databaseName=demo01
username: sa
password: 123456rw
1.4新建实体类绑定表
新建User表和数据库中表帮绑定
@Data
@TableName("user1")
public class User {
private Integer id;
private String name;
}
1.5 建Mapper接口
@Repository
public interface UserMapper extends BaseMapper<User> {
}
1.6让启动时扫描dao层mapper接口
@SpringBootApplication
@MapperScan("com.rw.Mapper")
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
1.7写接口去测试
@Controller
public class TestController {
@Autowired
private UserMapper userMapper;
@RequestMapping("getAllUser")
@ResponseBody//把返回值打印到页面(JSON)
public List<User> getAlluser(){
//queryWrapper 查询条件 如果过传递 null 就是查询所有数据
//先创建一个条件对象
QueryWrapper<User> queryWrapper=new QueryWrapper<>();
//添加条件
//eq 是等于 查询id==1 的数据
//queryWrapper.eq("id","2");
/**
* ne 是不等于
*/
//queryWrapper.ge("id","5");
//queryWrapper.between("id",2,5);
//queryWrapper.like("name","小");
queryWrapper.orderByDesc("id");
return userMapper.selectList(queryWrapper);
}
@ResponseBody
@RequestMapping("/add")
public String add(){
User user=new User();
user.setId(11);
user.setName("小王");
int insert = userMapper.insert(user);
if (insert>0){
return "添加成功!";
}else {
return "添加失败!";
}
}
@RequestMapping("/update")
@ResponseBody
public String update(){
//1.查询要修改的内容
User user = userMapper.selectById("3");
System.out.println(user);
//2.修改
user.setName("New Hello");
//userMapper.updateById() 根据你user的id进行修改
int i = userMapper.update(user,new QueryWrapper<User>().eq("id","3"));
if (i>0){
System.out.println("修改成功!");
return "修改成功!";
}else {
System.out.println("修改失败!");
return "修改失败";
}
}
@RequestMapping("/delete")
@ResponseBody
public String delete(){
//创建一个条件对象
QueryWrapper<User> wrapper=new QueryWrapper();
//添加条件
/**
* 删除的是 name=New Hello 这条数据
*/
wrapper.eq("name","New Hello");
int delete = userMapper.delete(wrapper);
if (delete>0){
return "删除成功!";
}else {
return "删除失败!";
}
}
}