<pre name="code" class="java">package com.test;
import java.io.IOException;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.alibaba.fastjson.JSON;
import com.common.DBUtil;
import com.model.Role;
import com.model.User;
import com.model.UserRoleKey;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:mybatis-config.xml" })
public class TestMybatis {
private static final Logger logger = Logger.getLogger(TestMybatis.class);
/**
* 查询所有数据
* @throws IOException
*/
@Test
public void getAll() throws IOException {
SqlSession session = DBUtil.getSessionFactory().openSession();
List<User> users = session.selectList("com.dao.UserMapper.getAll");
logger.info(JSON.toJSONStringWithDateFormat(users, "yyyy-MM-dd HH:mm:ss"));
session.close();
}
/**
* 根据主键获取表数据
* @throws IOException
*/
@Test
public void getUser() throws IOException {
SqlSession session = DBUtil.getSessionFactory().openSession();
User user = session.selectOne("com.dao.UserMapper.selectByPrimaryKey",1);
logger.info(JSON.toJSONStringWithDateFormat(user, "yyyy-MM-dd HH:mm:ss"));
session.close();
}
/**
* 添加表数据(不要忘记commit())
* @throws IOException
*/
@Test
public void insertUser() throws IOException {
SqlSession session = DBUtil.getSessionFactory().openSession();
User user = new User();
user.setId("1111");
user.setName("123123");
user.setPassword("asdasda");
user.setDescr("阿斯达");
user.setType(1);
session.insert("com.dao.UserMapper.insertSelective",user);
logger.info(JSON.toJSONStringWithDateFormat(user.getId(), "yyyy-MM-dd HH:mm:ss"));
UserRoleKey userRole = new UserRoleKey();
Role Role = session.selectOne("com.dao.RoleMapper.selectRoleByType",1);
logger.info(JSON.toJSONStringWithDateFormat(role, "yyyy-MM-dd HH:mm:ss"));
userRole.setRoleId(Role.getId());
userRole.setUserId(user.getId());
session.insert("com.dao.UserRoleMapper.insertSelective",userRole);
logger.info(JSON.toJSONStringWithDateFormat(userRole, "yyyy-MM-dd HH:mm:ss"));
session.commit();
session.close();
}
/**
* 根据主键修改表数据(commit())
* @throws IOException
*/
@Test
public void updateUser() throws IOException {
SqlSession session = DBUtil.getSessionFactory().openSession();
User user = session.selectOne("com.dao.UserMapper.selectByPrimaryKey",111);
user.setType(9);
session.update("com.dao.UserMapper.updateByPrimaryKeySelective",user);
session.commit();
session.close();
}
/**
* 根据主键删除表数据(commit())
* @throws IOException
*/
@Test
public void delUser() throws IOException {
SqlSession session = DBUtil.getSessionFactory().openSession();
session.delete("com.dao.UserRoleMapper.deleteByPrimaryKey",1111);
session.delete("com.dao.UserMapper.deleteByPrimaryKey",1111);
session.commit();
session.close();
}
}
mybatis 测试文件
最新推荐文章于 2024-05-14 11:01:45 发布