数据库
第一步:使用IDEA新建实体类
package Com.fvti.Myabtis.Account;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private Integer id;
private String username;
private String password;
private String gender;
}
第二步:创建Mapper接口
package Com.fvti.Myabtis.Dao;
import Com.fvti.Myabtis.Account.Person;
import org.apache.ibatis.annotations.Select;
import org.w3c.dom.ls.LSInput;
import java.util.List;
public interface PersonMapper {
@Select("select * from test.user")
List<Person> findAllPerson();
}
第三步:修改Mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--引入外部文件-->
<properties resource="db.properties"/>
<!---->
<settings>
<setting name="logImpl" value="Log4j"/>
<!--配置全局默认缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
<!--设置别名-->
<!-- <typeAliases>
<typeAlias type="Com.MyStudy.Bean.User" alias="user"></typeAlias>
<typeAlias type="Com.MyStudy.Bean.Bboss" alias="boss"></typeAlias>
</typeAliases>-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="Com.fvti.Myabtis.Dao.PersonMapper"/>
</mappers>
</configuration>
由于使用了注解开发,mapper对应的映射文件就不需要了
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
第四步:测试
package Com.fvti.Myabtis.Test;
import Com.fvti.Myabtis.Account.Person;
import Com.fvti.Myabtis.Dao.PersonMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
public class MybatisPerson {
public static void main(String[] args) throws IOException {
Reader resourceAsReader = Resources.getResourceAsReader("Mybatis-Config.xml");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsReader);
SqlSession sqlSession = build.openSession();
PersonMapper mapper = sqlSession.getMapper(PersonMapper.class);
List<Person> allPerson = mapper.findAllPerson();
allPerson.forEach(tem->{
System.out.println(tem);
});
sqlSession.close();
}
}
运行结果: