Mybatis的增删改查

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Mybatis的增删改查

相关的接口例子如下

public interface UserOneMapper {

UserOne getuserByid(int i);

List getuserones();

void insertone(UserOne userone);

void deleteonebyid(Integer id);

void deleteonebyname(String user_name);

void updateone(UserOne userone);

}

相关的java代码

public class TestMybatis {

private SqlSession sqlsession;

public void selectall() {

List list=new ArrayList();

try{

sqlsession=UtileMybatis.getsqlsession();

UserOneMapper mapper=sqlsession.getMapper(UserOneMapper.class);

list=mapper.getuserones();

for(UserOne user:list){

System.out.println(user);

}

}finally{

if(sqlsession!=null){

sqlsession.close();

}

}

}

public void selectone() {

try{

sqlsession=UtileMybatis.getsqlsession();

UserOneMapper mapper=sqlsession.getMapper(UserOneMapper.class);

UserOne userone=mapper.getuserByid(1);

System.out.println(userone);

}finally{

if(sqlsession!=null){

sqlsession.close();

}

}

}

public void insertone() {

try{

sqlsession=UtileMybatis.getsqlsession();

UserOneMapper mapper=sqlsession.getMapper(UserOneMapper.class);

UserOne user=new UserOne(4,"ddd","7879",45,"nan");

mapper.insertone(user);

mit();

}finally{

if(sqlsession!=null){

sqlsession.close();

}

}

}

public void deleteone() {

try{

sqlsession=UtileMybatis.getsqlsession();

UserOneMapper mapper=sqlsession.getMapper(UserOneMapper.class);

mapper.deleteonebyid(1);

mit();

}finally{

if(sqlsession!=null){

sqlsession.close();

}

}

}

public void deletetwobyname() {

try{

sqlsession=UtileMybatis.getsqlsession();

UserOneMapper mapper=sqlsession.getMapper(UserOneMapper.class);

mapper.deleteonebyname("dada");

mit();

}finally{

if(sqlsession!=null){

sqlsession.close();

}

}

}

@Test

//根据相关属性修改对象其他内容

public void updateone() {

try{

sqlsession=UtileMybatis.getsqlsession();

UserOneMapper mapper=sqlsession.getMapper(UserOneMapper.class);

UserOne userone=new UserOne(3,"ddd","7894",79,"nu");

mapper.updateone(userone);

mit();

}finally{

if(sqlsession!=null){

sqlsession.close();

}

}

}

}

Mapper的映射文件

insert into userone(id,user_name,password,age,sex)

values(#{id},#{user_name},#{password},#{age},#{sex})

delete from userone where id = #{id}

delete from userone where user_name = #{user_name}

update userone set id = #{id},password =#{password},age =#{age},sex =#{sex} where user_name=#{user_name}

如果要获取自增主键的值就要在标签中加入

BEFORE运行顺序

先查出id

useGeneratedkeys=”true”,keyproperty=”id”,order=”AFTER”

AFTER运行顺序

先运行sql

所需要注意的是

相关文档
最新文档