Mybatis开发环境搭建实现数据的增删改查功能

作者:袖梨 2022-11-14

config.xml的配置

代码如下 复制代码

"http://mybatis.org/dtd/mybatis-3-config.dtd">

使用xml需要再配置一个mappen.xml

代码如下 复制代码

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

insert into user values (null,#{name},#{password},#{age})

使用注解则用接口

publicinterfaceUserImpl {

//更新用户,更新用@update,查询用@select,插入用@insert,删除使用@delete这些注解

@Update("update user set name=#{name} where id=#{id}")

publicvoidupdateUser(User user);

}

demo测试代码

publicclassDemo {

staticInputStream in =null;

staticSqlSessionFactory ssf =null;

static{

in = Demo.class.getClassLoader().getResourceAsStream("config.xml");

ssf =newSqlSessionFactoryBuilder().build(in);

}

publicstaticvoidmain(String[] args) {

//selectAll();

//insertUser();

updateUser();

}

//查询全部

publicstaticvoidselectAll(){

SqlSession session = ssf.openSession();

List list = session.selectList("com.leige.entity.UserMappen.selectAll");

System.out.println(list);

session.close();

}

//增加用户

publicstaticvoidinsertUser(){

SqlSession session = ssf.openSession();

User user =newUser();

user.setName("小霸王");

user.setPassword("aaaaa");

user.setAge(25);

intnum = session.insert("com.leige.entity.UserMappen.insertUser",user);

session.commit();

System.out.println(num);

session.close();

}

//修改用户信息

publicstaticvoidupdateUser(){

SqlSession session = ssf.openSession();

UserImpl userImpl = session.getMapper(UserImpl.class);

User user =newUser();

user.setName("我是大头鬼");

user.setPassword("aaaaa");

user.setAge(25);

user.setId(79);

userImpl.updateUser(user);

session.commit();

session.close();

}

}

相关文章

精彩推荐