分享

Mybatis第二天

 新进小设计 2020-02-28

第二天讲义地址

crud

注意事项

http://static....
1创建maven工程
2导入依赖
3编写SqlMapConfig.xml
image.png
类似于org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.itheima.dao.IUserDao.findById错误表示没在IUserDao.xml中配置查询的参数

Error querying database. Cause: org.apache.ibatis.executor.ExecutorException: A query was run and no Result Maps were found for the Mapped Statement 'com.itheima.dao.IUserDao.findByQueryVo'. It's likely that neither a Result Type nor a Result Map was specified.

The error may exist in com/itheima/dao/IUserDao.xml

表示没有指定返回值的接收类型

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-////DTD Config 3.0//EN"
"http:///dtd/mybatis-3-config.dtd">
<configuration>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource> </environment> </environments> <mappers> <mapper resource="com/itheima/dao/IUserDao.xml"></mapper>
</mappers></configuration>

IUserDao.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-////DTD Mapper 3.0//EN"
"http:///dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.IUserDao">
<!-- <select id="findAll" resultType="com.itheima.domain.User">-->
<!-- select * from user;-->
<!-- </select>-->
<!-- <insert id="saveUser" parameterType="com.itheima.domain.User">-->
<!-- <selectKey keyProperty="id" keyColumn="id" resultType="int" order="AFTER">-->
<!-- select last_insert_id();-->
<!-- </selectKey>-->
<!-- insert into user(username,address,sex,birthday) values (#{username},#{address},#{sex},#{birthday});-->
<!-- </insert>-->
<!-- <update id="updateUser" parameterType="com.itheima.domain.User">-->
<!-- update user set username = #{username},address=#{address},sex=#{sex},birthday=#{birthday} where id = #{id};-->
<!-- </update>-->
<!-- <delete id="deleteUser" parameterType="java.lang.Integer">-->
<!-- delete from user where id = #{id};-->
<!-- </delete>-->
<!-- <select id="findById" parameterType="java.lang.Integer" resultType="com.itheima.domain.User">-->
<!-- select * from user where id = #{id};-->
<!-- </select>-->
<!-- <select id="findByUsername" parameterType="String" resultType="com.itheima.domain.User">-->
<!-- select * from user where username like #{username};-->
<!-- </select>-->
<!-- <select id="total" resultType="java.lang.Integer">-->
<!-- select count(*) from user;-->
<!-- </select>-->
<!-- <select id="findByQueryVo" parameterType="com.itheima.domain.QueryVo" resultType="com.itheima.domain.User">-->
<!-- select * from user where username like #{user.username};-->
<!-- </select>-->

<!-- 配置 查询结果的列名和实体类的属性名的对应关系 -->
<resultMap id="userMap" type="com.itheima.domain.User">
<!-- 主键字段的对应 -->
<id property="userId" column="id"></id>
<!--非主键字段的对应-->
<result property="userName" column="username"></result>
<result property="userAddress" column="address"></result>
<result property="userSex" column="sex"></result>
<result property="userBirthday" column="birthday"></result>
</resultMap> <!--以上是为更改类之前的,以下是更改类之后的-->
<select id="findAll" resultMap="userMap">
select * from user;

</select>  

<insert id="saveUser" parameterType="com.itheima.domain.User">
<selectKey keyProperty="userId" keyColumn="id" resultType="int" order="AFTER">
select last_insert_id();

    </selectKey>  

insert into user(username,address,sex,birthday) values (#{userName},#{userAddress},#{userSex},#{userBirthday});

</insert>  

<update id="updateUser" parameterType="com.itheima.domain.User">
update user set username = #{userName},address=#{userAddress},sex=#{userSex},birthday=#{userBirthday} where id = #{userId};

</update>  

<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id = #{id};

</delete>  

<select id="findById" parameterType="java.lang.Integer" resultMap="userMap">
select * from user where id = #{id};

</select>  

<select id="findByUsername" parameterType="String" resultMap="userMap">
select * from user where username like #{userName};

</select>  

<select id="total" resultType="java.lang.Integer">
select count(*) from user;

</select>  

<select id="findByQueryVo" parameterType="com.itheima.domain.QueryVo" resultMap="userMap">
select * from user where username like #{user.userName};

</select>  

</mapper>
已上代码中只有通过id去查的SQL在更改User类的属性名的时候不需要再sql语句里边体现

User.java

package com.itheima.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable {

/\*private Integer id;  

private String username; private Date birthday; private String address; private String sex;

public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public Date getBirthday() { return birthday; }
public void setBirthday(Date birthday) { this.birthday = birthday; }
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
public String getSex() { return sex; }
public void setSex(String sex) { this.sex = sex; }
@Override public String toString() { return "User{" + "id=" + id + ", username='" + username + '\'' + ", birthday=" + birthday + ", address='" + address + '\'' + ", sex='" + sex + '\'' + '}'; }*/ private Integer userId;
private String userName;
private Date userBirthday;
private String userAddress;
private String userSex;

public Integer getUserId() {

    return userId;  

}

public void setUserId(Integer userId) {  
    this.userId \= userId;  

}

public String getUserName() {  
    return userName;  

}

public void setUserName(String userName) {  
    this.userName \= userName;  

}

public Date getUserBirthday() {  
    return userBirthday;  

}

public void setUserBirthday(Date userBirthday) {  
    this.userBirthday \= userBirthday;  

}

public String getUserAddress() {  
    return userAddress;  

}

public void setUserAddress(String userAddress) {  
    this.userAddress \= userAddress;  

}

public String getUserSex() {  
    return userSex;  

}

public void setUserSex(String userSex) {  
    this.userSex \= userSex;  

}

@Override  

public String toString() {

    return "User{" +  
            "userId=" \+ userId +  
            ", userName='" \+ userName \+ '\\'' +  
            ", userBirthday=" \+ userBirthday +  
            ", userAddress='" \+ userAddress \+ '\\'' +  
            ", userSex='" \+ userSex \+ '\\'' +  
            '}';  

}
}

IUserDao.java

package com.itheima.dao;

import com.itheima.domain.QueryVo;
import com.itheima.domain.User;

import java.util.List;

public interface IUserDao {

/\*\*  

* 查询所有用户
*/
List<User> findAll();
/**
* 添加用户
*/
void saveUser(User user);
/**
* 修改用户
*/
void updateUser(User user);

/**
* 删除用户
* @param id
*/
void deleteUser(Integer id);

/**
* 查找的单个用户
* @param id
* @return
*/
User findById(Integer id);

/**
* 根据用户名模糊查询
* @param username
* @return
*/
List<User> findByUsername(String username);

/**
* 总用户数
* @return
*/
int total();

/**
* 封装查询条件到对象
* @param q
* @return
*/
List<User> findByQueryVo(QueryVo q);
}

MybatisTest.java

package com.itheima.test;

import com.itheima.dao.IUserDao;
import com.itheima.domain.QueryVo;
import com.itheima.domain.User;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.jws.soap.SOAPBinding;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MybatisTest {

private InputStream in;  

private SqlSession sqlSession;
private IUserDao userDao;

/**
* 在测试方法前执行
* @throws IOException
*/ @Before
public void init () throws IOException {

    //读取配置文件  

in = Resources.getResourceAsStream("SqlMapConfig.xml");
//获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//获取SqlSession对象
sqlSession = factory.openSession();
//获取userDao代理对象
userDao = sqlSession.getMapper(IUserDao.class);
}

/\*\*  

* 在测试方法后执行
*/
@After
public void destroy() throws IOException {

    sqlSession.commit();  

sqlSession.close();
in.close();
}

@Test  

public void testFindAll(){

    List<User> list = userDao.findAll();  

for(User user:list){

        System.out.println(user);  

}

}  

@Test  

public void testSaveUser(){

    User user = new User();  

user.setUserName("张三");
user.setUserAddress("北京.和平路");
user.setUserSex("男");
user.setUserBirthday(new Date());
System.out.println("操作添加之前:"+user);
userDao.saveUser(user);
System.out.println("操作添加之后:"+user);
}

@Test  

public void testUpdateUser() throws ParseException {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  

Date date = dateFormat.parse("1992-08-09 12:00:09");
User user = new User();
user.setUserId(51);
user.setUserName("张三x");
user.setUserAddress("南京鼓楼");
user.setUserSex("男");
user.setUserBirthday(date);
System.out.println("操作添加之前:"+user);
userDao.updateUser(user);
System.out.println("操作添加之后:"+user);
}

@Test  

public void testDeleteUser(){

    User user = new User();  

userDao.deleteUser(51);
}

@Test  

public void testFindById(){

    User user = userDao.findById(51);  

System.out.println(user);
}

@Test  

public void testFindByUsername(){

    List<User> list = userDao.findByUsername("%小%");  

for (User user : list){

        System.out.println(user);  

}

}  

@Test  

public void testTotal(){

    int count = userDao.total();  

System.out.println(count);
}

@Test  

public void testFindByQueryVo(){

    QueryVo query = new QueryVo();  

User user = new User();
user.setUserName("%王%");
query.setUser(user);
List<User> list = userDao.findByQueryVo(query);
for (User u:list){

        System.out.println(u);  

}

}  

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多