发表于: 2018-10-19 23:11:32
1 388
今天完成的事情:
复习mybatis的注解方式
MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以对配置和原生Map使用简单的 XML 或注解,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
一。mybatis简单注释
关键注解词
@Insert:和xml insert sql语法完全一样
@select:和xml select sql 语法完全一样
@update:和xml update sql 语法完全一样
@delete:和xml delete sql 语法完全一样
步骤一,建立连接数据库配置文件,实体类
<?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>
<!--<typeAliases>-->
<!--<package name="com.lyh.pojo"/>-->
<!--</typeAliases>-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://188.131.142.171:3306/tesk?characterEncoding=utf-8&useSSL=true"/>
<property name="username" value="root"/>
<property name="password" value="123456789"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--<mapper resource="Category.xml"/>-->
<mapper class="com.lyh.interface1.StudentsMapper"/>
</mappers>
</configuration>
步骤二,建立接口类mapper
public interface StudentsMapper {
@Insert("insert into students(name,qq,wish,school,enrolment_time,type,know_from,create_at,update_at) values(#{name},#{qq},#{wish},#{school},#{enrolment_time},#{type},#{know_from},#{create_at},#{update_at})")
@Options(useGeneratedKeys = true)
public int add(Students students);
@Delete("delete from students where id = #{id} ")
public void delete(int id);
@Update("update students set name = #{name} where id = #{id}")
public void update(Students students);
@Select("select * from students where id = #{id}")
public Students select(int id );
@Select("select * from students ")
public List<Students> getAllStudents();
}
步骤三,建立工具类mybatisUntil用于加载关联的映射文件
public class MybatisUntil {
public static SqlSessionFactory getFactory(){
String resource="MybatisConfig.xml";
//加载mybatis 的配置文件(它也加载关联的映射文件)
InputStream is= MybatisUntil.class.getClassLoader().getResourceAsStream(resource);
//构建sqlSession 的工厂
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
return factory;
}
}
步骤四,建立测试类开始mybatis注解测试
public class TestMybatis {
private static org.apache.log4j.Logger logger = Logger.getLogger(Test.class);
//mybatis注解测试
//批量插入,并返回主键id
@Test
public void testInsert(){
SqlSessionFactory factory = MybatisUntil.getFactory();
SqlSession session = factory.openSession(false);
StudentsMapper mapper = session.getMapper(StudentsMapper.class);
Students students = new Students();
students.setName("李和开机号白");
students.setQq(17540990);
students.setWish("简繁体个");
students.setSchool("灰身粉骨毁容");
students.setEnrolment_time(5468541);
students.setType("java");
students.setKnow_from("微信");
students.setCreate_at(84);
students.setUpdate_at(34564);
for (int i = 0; i < 2; i++) {
mapper.add(students);
logger.debug(students.getId());
}
session.commit();
session.close();
}
//删除操作
@Test
public void testDelete(){
SqlSessionFactory factory = MybatisUntil.getFactory();
SqlSession session = factory.openSession(false);
StudentsMapper mapper = session.getMapper(StudentsMapper.class);
mapper.delete(32);
session.commit();
session.close();
}
// 修改操作
@Test
public void testUpdate(){
SqlSessionFactory factory = MybatisUntil.getFactory();
SqlSession session = factory.openSession(false);
StudentsMapper mapper = session.getMapper(StudentsMapper.class);
Students students = new Students();
students.setName("花费的顾客");
students.setId(67);
mapper.update(students);
session.commit();
session.close();
}
// 根据id查找数据
@Test
public void select(){
SqlSessionFactory factory = MybatisUntil.getFactory();
SqlSession session = factory.openSession(false);
StudentsMapper mapper = session.getMapper(StudentsMapper.class);
Students students = mapper.select(89);
session.commit();
session.close();
System.out.println(students);
}
// 查询全部数据
@Test
public void selectAll(){
SqlSessionFactory factory = MybatisUntil.getFactory();
SqlSession session = factory.openSession(false);
StudentsMapper mapper = session.getMapper(StudentsMapper.class);
List<Students> students = mapper.getAllStudents();
//foreach增强for循环
for (Students students1 : students){
logger.debug(students1);
}
session.commit();
session.close();
}
}
命名空间(Namespaces)在之前版本的 MyBatis 中是可选的,容易引起混淆因此是没有益处的。现在的命名空间则是必须的,目的是希望能比只是简单的使用更长的完全限定名来区分语句更进一步。
命名解析:为了减少输入量,MyBatis 对所有的命名配置元素(包括语句,结果映射,缓存等)使用了如下的命名解析规则。
SqlSessionFactoryBuild
这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但是最好还是不要让其一直存在以保证所有的 XML 解析资源开放给更重要的事情。
映射器实例
映射器是创建用来绑定映射语句的接口。映射器接口的实例是从 SqlSession 中获得的。因此从技术层面讲,映射器实例的最大作用域是和 SqlSession 相同的,因为它们都是从 SqlSession 里被请求的。尽管如此,映射器实例的最佳作用域是方法作用域。也就是说,映射器实例应该在调用它们的方法中被请求,用过之后即可废弃。并不需要显式地关闭映射器实例,尽管在整个请求作用域(request scope)保持映射器实例也不会有什么问题,但是很快你会发现,像 SqlSession 一样,在这个作用域上管理太多的资源的话会难于控制。所以要保持简单,最好把映射器放在方法作用域(method scope)内。
mybatis使用注解方式插入数据后获得自增长的id值
1. 写SQL,但不要自己插入主键值
2. 配置@Options(useGeneratedKeys=true, keyProperty="对象.属性") 这个的作用是设置是否使用JDBC的getGenereatedKeys()方法获取主键并赋值到keyProperty设置的对象的属性中,说白了就是把自增长的主键值赋值给对象相应的属性
3. 在插入后,使用对象.主键属性的getXXId()方法 获取主键值
@Insert("insert into students(name,qq,wish,school,enrolment_time,type,know_from,create_at,update_at) values(#{name},#{qq},#{wish},#{school},#{enrolment_time},#{type},#{know_from},#{create_at},#{update_at})")
@Options(useGeneratedKeys = true)
public int add(Students students);
添加上面的第三行就可以了,其中第二个参数据说可以不需要
添加该注解后
在数据库中添加成功后,product的id属性就会被默认赋值。
for (int i = 0; i < 2; i++) {
mapper.add(students);
logger.debug(students.getId());
}
session.commit();
session.close();
明天计划的事情:
复习spring整合mybatis,学习基本知识
遇到的问题:
无
收获:
收获比较少,还要多练几遍
评论