java调用mybatis_java Mybatis使用

本文介绍了如何在Java中调用MyBatis进行数据库操作,包括通过StoreMapper接口定义SQL语句,如获取单个信息、列表数据以及分页查询。同时展示了StoreService类中如何注入并使用StoreMapper与JdbcTemplate,以及如何使用PageHelper进行分页处理。在输出层,将分页查询结果转化为JSON对象返回。
摘要由CSDN通过智能技术生成

1.StoreMapper Mapper

import com.github.pagehelper.Page;

import com.luyi.apiservice.models.Store;

import org.apache.ibatis.annotations.Mapper;

import org.springframework.stereotype.Repository;

import java.util.List;

import java.util.Map;

@Repository

@Mapper

public interface StoreMapper {

Store getInfoById(int id);

List getList();

Page getListPage(Map param);

}

2.StoreMapping.xml

select * from ly_store where id = #{id}

select * from ly_store limit 0,10

select id, name, mobile, created_at from ly_store

3.StoreService

import com.github.pagehelper.Page;

import com.luyi.apiservice.mapper.StoreMapper;

import com.luyi.apiservice.models.Store;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import java.util.Map;

@Service

@Transactional

public class StoreService {

@Autowired

StoreMapper storeMapper;

@Autowired

JdbcTemplate jdbcTemplate;

// 获取用户信息

public Store getStoreById(int id){

return storeMapper.getInfoById(id);

}

public List getList(){

return storeMapper.getList();

}

public Page getSListByLimit(Map param){

System.out.println(param);

return storeMapper.getListPage(param);

}

/**

* 获取单个信息

* @param name

* @return

*/

public String getNameById(Integer store_id,String name){

if(store_id > 0){

if(name == null){

name = "name";

}

String sql = "select "+name+" from ly_store where id=?";

try {

String info = jdbcTemplate.queryForObject(sql,new Object[]{store_id},String.class);

return info;

} catch (Exception e) {

e.printStackTrace();

return null;

}

}

return null;

}

// 获取分页数据

public Page getListByPage(Integer page){

Page list = newsMapper.getListByPage(page);

for( News info: list) {

String img = AppConstant.WEB_URL+info.getImage();

info.setImage(img);

}

return list;

}

}

5.输出层

PageHelper.startPage(page,10);

Page data = newsService.getListByPage(page);

JSONObject result = new JSONObject();

result.put("list",data);

result.put("pages",data.getPages());

result.put("last_page",data.getPages());

result.put("total",data.getTotal());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值