MyBatis实现CRUD
项目主要结构,包含实体类domain,CRUD操作接口mapper,主类,yml配置文件,测试类
可以根据需求来编写controller和service层,这里只在控制台进行测试所以不再展示
在springboot数据库中建表account
DROP TABLE IF EXISTS account;
CREATE TABLE account (
ID int(11) NOT NULL COMMENT 'ID',
UID int(11) default NULL COMMENT 'UID',
MONEY double default NULL COMMENT 'MONEY',
PRIMARY KEY (ID)
)
insert into account(ID,UID,MONEY) values (1,41,1000),(2,45,1000),(3,41,2000);
定义实体类account
public class Account {
private int id;
private int uid;
private double money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", uid=" + uid +
", money=" + money +
'}';
}
}
编写mapper的各接口
查询全部,id查询,插入,id删除,更新
import com.example.springbootmybatis.domain.Account;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface AccountMapper {
@Select("select * from account")
public List<Account> selectAllAccount();
@Select("select * from account where id = #{id}")
List<Account> selectOne(Integer id);
@Insert("insert into account(id,uid,money) values(#{id},#{uid},#{money})")
int insert(Account account);
@Delete("delete from account where id = #{id}")
int deleteById (Integer id);
@Update("update account set id=#{id},uid=#{uid},money=#{money} where id = #{id}")
int updateById(Account account);
}
主类中添加扫描器
在yml中进行配置
mysql指定数据库、用户、密码、驱动等
spring:
datasource:
url: jdbc:mysql:///springboot
username: root
password: 111111
driver-class-name: com.mysql.jdbc.Driver
测试
最后在测试类中注入Mapper,即可在测试类中根据需求进行测试
相当简陋