今天学习MyBatis时写sql遇到了问题,所以就写了,咋们废话不多说直接上代码:
首先使数据库方面sql代码:
use mybatis;
create table t_account(
id int primary key auto_increment,
username VARCHAR(11),
password VARCHAR(11),
age int
)
运行结果
我这边添加数据后:
定义字段的Account:
package com.fzf.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
private long id;
private String username;
private String password;
private int age;
}
AccountRepository接口类
package com.fzf.repository;
import com.fzf.entity.Account;
import java.util.List;
public interface AccountRepository {
public Account findByNameAndAge(String name,int age);
}
测试的Test2
package com.fzf.test;
import com.fzf.entity.Account;
import com.fzf.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.List;
public class Test2 {
public static void main(String[] args) {
InputStream inputStream=Test.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory=sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession=sqlSessionFactory.openSession();
//获取实现接口的代理对象
AccountRepository accountRepository=sqlSession.getMapper(AccountRepository.class);
System.out.println(accountRepository.findByNameAndAge("张三",22));
sqlSession.close();
}
}
AccountRepository.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fzf.repository.AccountRepository">
<select id="findByNameAndAge" resultType="com.fzf.entity.Account">
select * from t_account where username = #{param0}and age = #{param1}
</select>
</mapper>
书写方法就是AccountRepository.xml中select写法,#{}里面写param1,param2或者写arg0,arg1,不然就会报错:
最后我们查询成功,nice!