SqlSession session=factory.openSession();
//使用Mapper接口
IUserDao userDao=session.getMapper(IUserDao.class);
List users = userDao.findAll();
自己写实现类:
SqlSession session = factory.openSession();
//使用Sqlsession对象执行查询所有方法,直接使用Sqlsession
List list = session.selectList("com.itheima.dao.IUserDao.findAll");
session.close();
JDBC:
Class.forName("com.mysql.cj.jdbc.Driver");
//3.获取数据库连接
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/mydate?serverTimezone=UTC","root","root");
//4.定义sql语句
String sql="delete from student2 where id =1";
//5.获取执行sql语句的对象statement
Statement stmt=conn.createStatement();
//6.执行sql,接受返回结果
int count=stmt.executeUpdate(sql);
//7.处理结果
System.out.println(count);
//8.释放资源
stmt.close();
conn.close();
select * from mybatis where and username like #{username}
@Test
public void testFindByUser() {
User u = new User(); u.setUsername("%王%");
u.setAddress("%顺义%");
//6.执行操作
List users = userDao.findByUser(u);
for(User user : users) {
System.out.println(user);
}
}
where标签
< foreach>标签
传入多个id查询用户信息,用下边两个sql实现:
SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)
SELECT * FROM USERS WHERE username LIKE '%张%' AND id IN (10,89,16)
QueryVo1.java
package domain;
import java.io.Serializable;
import java.util.List;
public class QueryVo1 implements Serializable {
private List ids;
public List getIds() {
return ids;
}
public void setIds(List ids) {
this.ids = ids;
}
}
测试:
@Test
public void testfindInIds(){
QueryVo1 vo1 = new QueryVo1();
List ids = new ArrayList();
ids.add(8);
ids.add(9);
ids.add(10);
ids.add(14);
vo1.setIds(ids);
List inIds = mapper.findInIds(vo1);
System.out.println(inIds);
拼接sql语句
DEBUG - ==> Preparing: select * from mybatis WHERE id in ( ? , ? , ? , ? )
DEBUG - ==> Parameters: 8(Integer), 9(Integer), 10(Integer), 14(Integer)
DEBUG - <== Total: 4
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String address;
private String sex;
private List accountList;
public List getAccountList() {
return accountList;
}
...
}
使用collection实现延迟加载
测试类
@Test
public void testFindAccountByUserId(){
List allUser = mapper.findAllUser();
for(User i:allUser){
System.out.println("user:"+i.getId()+"账户-----------------------------------");
List accountList = i.getAccountList();
for(Account j:accountList){
System.out.println("账户id"+j.getId());
System.out.println("账户所属user"+j.getUser().getId());
}
}
}
public interface IUserDao {
/**
* 查询所有用户
* @return
*/
@Select("select * from user")
List findAll();
/**
* 保存用户
* @param user
*/
@Insert("insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})")
void saveUser(User user);
/**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
void updateUser(User user);
/**
* 删除用户
* @param userId
*/
@Delete("delete from user where id=#{id} ")
void deleteUser(Integer userId);
/**
* 根据id查询用户
* @param userId
* @return
*/
@Select("select * from user where id=#{id} ")
User findById(Integer userId);
/**
* 根据用户名称模糊查询
* @param username
* @return
*/
// @Select("select * from user where username like #{username} ")
@Select("select * from user where username like '%${value}%' ")
List findUserByName(String username);
/**
* 查询总用户数量
* @return
*/
@Select("select count(*) from user ")
int findTotalUser();
}
注意:注解开发的时候resource相同文件路径下不能有对应的xml文件 不然报错
实体类属性和数据库类名的对应关系
基于注解的一对一
@Select("select * from account")
@Results(id="accountMap",value = {
@Result(id=true,column = "id",property = "id"),
@Result(column = "uid",property = "uid"),
@Result(column = "money",property = "money"),
@Result(property = "user",column = "uid", one=@One(select="com.itheima.dao.IUserDao.findById",fetchType= FetchType.EAGER))
})
List findAll();
@Select("select * from user where id=#{id}")
@ResultMap("userMap")
User findById(Integer userId);
基于注解的一对多
@Select("select * from user")
@Results(id="userMap",value={
@Result(id=true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "address",property = "userAddress"),
@Result(column = "sex",property = "userSex"),
@Result(column = "birthday",property = "userBirthday"),
@Result(column = "id",property = "accounts",
many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
fetchType = FetchType.LAZY))
})
List findAll();
@Select("select * from account where uid = #{userId}")
List findAccountByUid(Integer userId);
基于注解的一级缓存和二级缓存
注解的默认带有一级缓存 使用方法与基于xml形式一样
二级缓存
现在sqlMapConfig.xml中添加
2.在dao上添加注解@CacheNamespace(blocking = true)
@CacheNamespace(blocking = true)
public interface IUserDao {
测试类
public class SecondLevelCatchTest {
private InputStream in;
private SqlSessionFactory factory;
@Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
factory = new SqlSessionFactoryBuilder().build(in);
}
@After
public void destroy()throws Exception{
in.close();
}
@Test
public void testFindOne(){
SqlSession session = factory.openSession();
IUserDao userDao = session.getMapper(IUserDao.class);
User user = userDao.findById(57);
System.out.println(user);
session.close();//释放一级缓存
SqlSession session1 = factory.openSession();//再次打开session
IUserDao userDao1 = session1.getMapper(IUserDao.class);
User user1 = userDao1.findById(57);
System.out.println(user1);
session1.close();
}
}
log4j:WARN No appenders could be found for logger (org.apache.ibatis.logging.LogFactory).
log4j:WARN Please initialize the log4j system properly.
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ibatis.reflection.Reflector (file:/C:/SoftWare/apache-maven/maven-repository/org/mybatis/mybatis/3.3.1/mybatis-3.3.1.jar) to method java.lang.Class.checkPackageAccess(java.lang.SecurityManager,java.lang.ClassLoader,boolean)
WARNING: Please consider reporting this to the maintainers of org.apache.ibatis.reflection.Reflector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
在客户端访问subversion版本库时出现这个错误:
svnserve.conf:12: Option expected
为什么会出现这个错误呢,就是因为subversion读取配置文件svnserve.conf时,无法识别有前置空格的配置文件,如### This file controls the configuration of the svnserve daemon, if you##
什么是Akka
Message-Driven Runtime is the Foundation to Reactive Applications
In Akka, your business logic is driven through message-based communication patterns that are independent of physical locatio
zabbix_api网上比较多的写法是python或curl。上次我用java--http://bossr.iteye.com/blog/2195679,这次用perl。for example: #!/usr/bin/perl
use 5.010 ;
use strict ;
use warnings ;
use JSON :: RPC :: Client ;
use
package com.test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class TestMap {
public static v
MySQL server has gone away 问题解决方法,需要的朋友可以参考下。
应用程序(比如PHP)长时间的执行批量的MYSQL语句。执行一个SQL,但SQL语句过大或者语句中含有BLOB或者longblob字段。比如,图片数据的处理。都容易引起MySQL server has gone away。 今天遇到类似的情景,MySQL只是冷冷的说:MySQL server h
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml&