SpringBoot+MyBatis连接数据库

SpringBoot通过MyBatis连接数据库有2种方法:

  • 1.注解

  • 2.XML文件

1.注解

1.构建项目

2.添加依赖:

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 引入starter-->
		<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>
		<!-- MySQL的JDBC驱动包	-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- 引入第三方数据源 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.6</version>
		</dependency>
	</dependencies>

3.配置属性文件:

#mybatis.type-aliases-package=net.xdclass.base_project.domain
#可以自动识别
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =password
#如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource)
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
#控制台打印sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

4.启动类(SpringApplication)添加mapper扫描

@MapperScan("net.xdclass.base_project.mapper")

5.开发Mapper,Mapper类是访问数据库的接口

public interface UserMapper{
	@Insert("Insert into user(name,phone,create_time,age) values(#{name},#{phone},#{createTime},#{age})")
	int insert(User user);
}

添加@Options(userGeneratedKeys=true,keyProperty="id",keyColumn="id") //key Property java对象的属性,key Column表示数据库的字段

6.添加User用户(domain)

public class User {

	private int id;
	
	private String name;
	
	private String phone;
	
	private int age;
	
	private Date createTime;
	xxx(相应的get/set方法)
}

7.添加service层

UserService:
public interface UserService {
	public int add(User user);
	
}

UserServiceImpl:
@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserMapper userMapper;
	@Override
	public int add(User user) {
		userMapper.insert(user);
		int id = user.getId();
		return id;
	}
}

8.添加Controller层

@RestController
@RequestMapping("/api/v1/user")
public class UserController {	
	@Autowired
	private UserService userService;
	
	@GetMapping("add")
	public Object add(){
		User user = new User();
		user.setAge(11);
		user.setCreateTime(new Date());
		user.setName("xdclass");
		user.setPhone("10010000");
		int id = userService.add(user);
		return JsonData.buildSuccess(id);
	}
}

9.select,update, delete的使用

1.从数据转成对象

public interface userMapper{
	@Select("select * from user")
	@Results({
	@Result(column="数据库字段1",property="对象的字段1"),
	@Result(column="数据库字段2",property="对象的字段2")
	})
	List<User> getAll();

}

调用的时候(直接在controller给调用了):

	@GetMapping("findAll")
	public Object findAll(){		
	       return JsonData.buildSuccess(userMapper.getAll());
	}
JsonData类在同层目录下

2.根据id找对象(id怎么传进去-》findById调用的时候传入id)

public interface userMapper{
	@Select("Select * from user where id=#{id}")
	@Results({
	@Result(column="数据库字段1",property="对象的字段1"),
	@Result(column="数据库字段2",property="对象的字段2")	
})
	User findById(Long id);
}

3.更新数据库对象

public interface userMapper{
   @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
    void update(User user);
}

4.删除数据库对象

public interface userMapper{
    @Delete("DELETE FROM user WHERE id =#{userId}")
    void delete(Long userId);
}

2.XML文件

https://blog.csdn.net/lr131425/article/details/76269236(这里的model类文件写错了)
主要区别在于怎么样实现Mapper层
XML的代码在https://github.com/Winster-cheng/SpringBoot-JDBC

posted @ 2018-11-19 11:35  周景白炎  阅读(875)  评论(0编辑  收藏  举报