整合MyBatis
1. 加入依赖
需要在pom.xml加入以下依赖
2. 修改配置文件
在application.properties添加配置
#spring集成Mybatis环境
#pojo别名扫描包
mybatis.type-aliases-package=cn.cnn.info.pojo
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.config-location=classpath:mybatis/SqlMapConfig.xml
#spring.datasource.type=com.jolbox.bonecp.BoneCPDataSource
在src\main\resources\mapper路径下加入UserMapper.xml配置文件
select * from user
加载通用Mapper和分页助手
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
3. 编写Mapper
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import cn.cnn.info.pojo.User;
//extends com.github.abel533.mapper.Mapper
@Mapper
public interface UserMapper extends com.github.abel533.mapper.Mapper
@Select("select * from user where name like '%${value}%'")
public List
// 使用UserMapper.xml配置文件
public List
}
4. 编写Service和Controller
Service编写
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import cn.cnn.info.dao.UserDao;
import cn.cnn.info.dao.UserMapper;
import cn.cnn.info.pojo.User;
import cn.cnn.info.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Autowired
private UserMapper userMapper;
@Override
public List
List
return list;
}
@Override
public List
List
return list;
}
// 调用使用UserMapper.xml的Mapper
@Override
public List
List
return list;
}
// 使用通用Mapper和分页助手
@Override
public List
// 设置分页
PageHelper.startPage(page, rows);
// 查询数据
List
return list;
}
}
Controller编写
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.cnn.info.pojo.User;
import cn.cnn.info.service.UserService;
@RestController
@RequestMapping("user")
public class UserControlelr {
@Autowired
private UserService userService;
@RequestMapping("list")
public List
List
return list;
}
@RequestMapping("list/{name}")
public List
List
return list;
}
@RequestMapping("list/query")
public List
List
return list;
}
@RequestMapping("list/{page}/{rows}")
public List
List
return list;
}
}
浏览器地址栏输入:http://127.0.0.1:8080/user/list/query