StudentDao
package dao;
import domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import util.MySqlSessionFactory;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
public class StudentDao {
//dao中存储一个sqlsession属性
private SqlSession sqlSession = MySqlSessionFactory.getSqlSession(true);
//设计一个方法 查询所有学生 根据id进行排序 (升序、降序不一定)
// 设计一个参数 排序的方式 String flag
public List<Student> selectAllByOrder(String flag){//asc升序 desc降序
return sqlSession.selectList("selectAllByOrder",flag);
}
//设计一个方法,根据给定的学生id,修改学生性别
public void update(Student student){
sqlSession.update("update",student);
}
public void delete(Integer id){
sqlSession.delete("delete",id);
}
public Student selectOne(Integer id){
return sqlSession.selectOne("selectOne",id);
}
//设计一个方法 新增一条学生记录
public void insert(Student student){
sqlSession.insert("insert",student);//加载驱动,获取连接(连接池),创建状态参数
}
}
StudentMapper.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="dao.StudentDao">
<insert id="insert">
insert into newstudent values(#{id},#{name},#{sex},#{birth},#{ctime})
</insert>
<update id="update">
update newstudent set name = #{name},sex = #{sex},
birth = #{birth},
ctime = #{ctime} where id = #{id}
</update>
<delete id="delete">
delete from newstudent where id = #{id}
</delete>
<select id="selectOne" resultType="domain.Student">
select * from newstudent where id = #{id}
</select>
<select id="selectAllByOrder" resultType="domain.Student">
select * from newstudent order by id ${flag}
</select>
</mapper>
Configuration.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/newtest?useSSL=false&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="cy414ljh212,,,"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentMapper.xml"></mapper>
</mappers>
</configuration>
关键代码如上,其余代码省略