spring
spring配置
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl" scope="singleton"></bean>
public class SpringTest {
@Test
public void test1(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao1= (UserDao) app.getBean("userDao");
UserDao userDao2= (UserDao) app.getBean("userDao");
System.out.println(userDao1); //地址与2一样
System.out.println(userDao2);
}
}
如果为prototype,则地址不一样
<bean id="userDao" class="com.itheima.dao.impl.UserDaoImpl"
scope="singleton"
init-method="init"></bean>
public class StaticFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}
<bean id="userDao" class="com.itheima.factory.StaticFactory"
factory-method="getUserDao"></bean>
spring注解开发
注解开发bean
springMVC
AOP
mybatis
<?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="userMapper">
<!-- 查询数据-->
<select id="findAll" resultType="com.itheima.domain.User">
select * from tb_user
</select>
<!-- 插入数据-->
<insert id="add" parameterType="com.itheima.domain.User">
insert into tb_user values(#{id},#{username},#{password})
</insert>
<!-- 修改数据-->
<update id="update" parameterType="com.itheima.domain.User">
update tb_user set name=#{username},password=#{password} where id=#{id}
</update>
<!-- 删除操作-->
<delete id="delete" parameterType="java.lang.Integer">
delete from tb_user where id=#{id}
</delete>
<!-- 根据id查询-->
<select id="findById" parameterType="int" resultType="user">
select * from tb_user where id= #{id}
</select>
</mapper>
测试
public class MyBatisTest {
@Test
public void test1() throws IOException {
//获取配置文件
InputStream inputStream=Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数 namespace+id
List<User> userList = sqlSession.selectList("userMapper.findAll");
System.out.println(userList);
sqlSession.close();
}
//插入操作
@Test
public void test2() throws IOException {
//模拟要插入的数据
User user = new User();
user.setUsername("44334");
user.setPassword("222222");
//获取配置文件
InputStream inputStream=Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数 namespace+id
int insert = sqlSession.insert("userMapper.add", user);
//插入数据默认不提交事务
sqlSession.commit();
System.out.println(insert);
sqlSession.close();
}
//修改操作
@Test
public void test3() throws IOException {
//模拟要插入的数据
User user = new User();
user.setId(1);
user.setUsername("wwwww");
user.setPassword("666666");
//获取配置文件
InputStream inputStream=Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数 namespace+id
int insert = sqlSession.update("userMapper.update", user);
//插入数据默认不提交事务
sqlSession.commit();
System.out.println(insert);
sqlSession.close();
}
//删除操作
@Test
public void test4() throws IOException {
//获取配置文件
InputStream inputStream=Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数 namespace+id
int insert = sqlSession.delete("userMapper.delete", 3);
//插入数据默认不提交事务
sqlSession.commit();
System.out.println(insert);
sqlSession.close();
}
//根据id查找操作
@Test
public void test5() throws IOException {
//获取配置文件
InputStream inputStream=Resources.getResourceAsStream("sqlMapConfig.xml");
//获取session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取session回话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数 namespace+id
User user = sqlSession.selectOne("userMapper.findById", 2);
//插入数据默认不提交事务
sqlSession.commit();
System.out.println(user);
sqlSession.close();
}
}
Mybaties相应的API
第一步
第二步
返回值
mybatis重点用法
dao层
下面写接口,mybatis代理对象实现方法
package com.itheima.dao;
import com.itheima.domain.User;
import java.io.IOException;
import java.util.List;
public interface UserMapper {
//查询所有的用户
public List<User> findAll() throws IOException;
//根据id查找
public User findById(int id);
}
注意:
1.方法名,例如findAll(),是根据userMapper.xml中的id名一致
2.返回类型,要和userMapper.xml中的resultType类型一致
UserMapper.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.itheima.dao.UserMapper">
<!-- 查询数据-->
<select id="findAll" resultType="com.itheima.domain.User">
select * from tb_user
</select>
<!-- 插入数据-->
<insert id="add" parameterType="com.itheima.domain.User">
insert into tb_user values(#{id},#{username},#{password})
</insert>
<!-- 修改数据-->
<update id="update" parameterType="com.itheima.domain.User">
update tb_user set name=#{username},password=#{password} where id=#{id}
</update>
<!-- 删除操作-->
<delete id="delete" parameterType="java.lang.Integer">
delete from tb_user where id=#{id}
</delete>
<!-- 根据id查询-->
<select id="findById" parameterType="int" resultType="user">
select * from tb_user where id= #{id}
</select>
</mapper>
注意:
mapper中的namespace是需要代理的接口
sqlMapConfig.xml
是mybatis的全局配置文件
<?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标签来加载外部的properties文件-->
<properties resource="jdbc.properties"></properties>
<!-- 配置别名-->
<typeAliases>
<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>
</typeAliases>
<!-- 配置数据源的环境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件-->
<mappers>
<mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
注意:
<typeAliases>
<typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>
</typeAliases>
可以让上边的userMapper.xml中的resultType中的值简写
例如:
<select id="findAll" resultType="com.itheima.domain.User">
select * from tb_user
</select>
可以写成
<select id="findAll" resultType="user">
select * from tb_user
</select>
通过properties标签来加载外部的properties文件
<properties resource="jdbc.properties"></properties>
<!-- 加载映射文件-->
<mappers>
<mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
</mappers>
jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:23306/atguigudb
jdbc.username=root
jdbc.password=0071hanxiaolei
service层
serviceDemo
public class serviceDemo {
public static void main(String[] args) throws IOException{
公共代码
//加载mybatis基础配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//创建sql会话工厂
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream);
//连接会话
SqlSession sqlSession = build.openSession();
//加载映射
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
具体使用
//查询所有的用户
List<User> all = mapper.findAll();
System.out.println(all);
//根据id查找用户
User byId = mapper.findById(1);
System.out.println(byId);
}
}
package com.itheima.handler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class DateTypeHandler extends BaseTypeHandler<Date> {
//将java类型转换成数据库所需要的类型
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
long time = date.getTime();
preparedStatement.setLong(i,time);
}
//将数据库中的类型转换为java类型
//String参数 要转换的字段名称
//ResultSet 查询出的结果集
@Override
public Date getNullableResult(ResultSet resultSet, String s) throws SQLException {
//获取结果集中需要的数据(long) 转换成为Date类型返回
long aLong = resultSet.getLong(s);
Date date = new Date(aLong);
return date;
}
//将数据库中的类型转换为java类型
@Override
public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
long aLong = resultSet.getLong(i);
Date date = new Date(aLong);
return date;
}
//将数据库中的类型转换为java类型
@Override
public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
long aLong = callableStatement.getLong(i);
Date date = new Date(aLong);
return date;
}
}
在sqlMapConfig.xml中配置
<!-- 配置类型转换-->
<typeHandlers>
<typeHandler handler="com.itheima.handler.DateTypeHandler"></typeHandler>
</typeHandlers>
分页使用
第一步:
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.3.0</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>4.3</version>
</dependency>
高版本的pagehelper需要下面的方式使用,不能配方言参数
<!--配置分页助手插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
使用
//设置分页相关参数 当前页+每页显示的条数
PageHelper.startPage(1,1);
此时就会返回一条数据
// 获取与分页相关参数
PageInfo<User> userPageInfo = new PageInfo<>();
System.out.println(userPageInfo.getPageNum());
mybatis多表查询
<mappers>
注意写法这里的语法不能改动
<mapper resource="com.itheima.mapper/UserMapper.xml"></mapper>
<mapper resource="com.itheima.mapper/OrderMapper.xml"></mapper>
</mappers>
多表联查
实体类中的写法 Order
注意 private User user; 的写法;
package com.itheima.domain;
public class Order {
private int id;
private String ordertime;
private String total;
private User user;
@Override
public String toString() {
return "Order{" +
"id=" + id +
", ordertime='" + ordertime + '\'' +
", total='" + total + '\'' +
", user=" + user +
'}';
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrdertime() {
return ordertime;
}
public void setOrdertime(String ordertime) {
this.ordertime = ordertime;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
}
orderMapper.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.itheima.mapper.OrderMapper">
<resultMap id="orderMap" type="com.itheima.domain.Order">
<!-- 手动指定字段与实体属性的映射关系-->
<!-- column:数据表的字段名称-->
<!-- property实体的属性名称-->
<id column="uid" property="id"></id>
<result column="ordertime" property="ordertime"></result>
<result column="total" property="total"></result>
这与下面的 association 写法相同,写其中一种即可
<!-- <result column="uid" property="user.id"></result>-->
<!-- <result column="name" property="user.username"></result>-->
<!-- <result column="password" property="user.password"></result>-->
<!-- property:当前实体Order中的属性名称;-->
<!-- javaType:当前实体Order中的属性类型;-->
<association property="user" javaType="user">
<id column="uid" property="id"></id>
<result column="name" property="username"></result>
<result column="password" property="password"></result>
</association>
</resultMap>
这里使用resultMap的写法
<select id="findAllOrders" resultMap="orderMap">
SELECT * ,u.id,u.uid FROM orders u ,tb_user o WHERE u.uid=o.id
</select>
</mapper>
mybatis注解开发
将原来的映射改为包扫描
<mappers>
<!-- <mapper resource="com.itheima.mapper/UserMapper.xml"></mapper>-->
<!-- <mapper resource="com.itheima.mapper/OrderMapper.xml"></mapper>-->
<!-- 指定接口所在的包-->
<package name="com.itheima.mapper"/>
</mappers>
注解开发一对一
@Select("select * from orders o,tb_user u where u.id=o.uid ")
@Results({
@Result(column = "id",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(column = "name",property = "user.username"),
@Result(column = "id",property = "user.id"),
@Result(column = "password",property = "user.password"),
})
public List<Order> findAllByzhujie();
}
注解开发与xml配置开发不能同时使用
//一对一注解开发二
@Select("select * from orders")
@Results({
@Result(column = "id",property = "id"),
@Result(column = "ordertime",property = "ordertime"),
@Result(column = "total",property = "total"),
@Result(
property = "user", //要封装的属性名称
column = "uid", //根据哪个字段去查找user表的数据
javaType = User.class, //要封装的实体类型
one = @One(select = "com.itheima.mapper.UserMapper.findById")
)
})
public List<Order> findAllByzhujie();
这里的也必须用注解开发
@Select("select * from tb_user where id=#{id}")
public List<User> findById();
注解开发一对多开发
@Select("select * from tb_user")
@Results({
@Result(id = true,column = "id",property = "id"),
@Result(column = "name",property = "username"),
@Result(column = "password",property = "password"),
@Result(
property = "orderList",
column = "id",
javaType = List.class,
many = @Many(select = "com.itheima.mapper.OrderMapper.findByUid")
)
})
public List<User> findAllOrder();
@Select("select * from orders where uid = #{uid}")
public List<Order> findByUid();
}
注解开发多对多查询
相当于双表联查
ssm整合