不用寫mybatis映射文件,採用註解方式提供相應的sql語句和輸入參數,項目目錄以下java
<build> <resources> <!-- mapper.xml文件在java目錄下 --> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> </build> <dependencies> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.9</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <scope>compile</scope> </dependency> </dependencies>
package com.cc.entity; public class Student { private int id; private String stuno; private String name; private String classid; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStuno() { return stuno; } public void setStuno(String stuno) { this.stuno = stuno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassid() { return classid; } public void setClassid(String classid) { this.classid = classid; } @Override public String toString() { return "Student{" + "id=" + id + ", stuno='" + stuno + '\'' + ", name='" + name + '\'' + ", classid='" + classid + '\'' + '}'; } }
package com.cc.dao; import com.cc.entity.Student; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface StudentMapper { @Select("select * from student where id=#{id}") Student findById(@Param("id") int id); @Select("select * from student") List<Student> selectAll(); }
那麼還有一個問題,我想在註解中實現動態查詢那怎麼辦???案例以下mysql
@Mapper public interface DemandCommentMapper extends BaseMapper<DemandComment>{ @Select("SELECT " + "a.id as 'id',a.create_date as 'createDate',a.content as 'content'," + "a.parent_id as 'parentId',a.first_comment_id as 'firstCommentId'," + "b.id as 'fromUser.id',b.realname as 'fromUser.realname',b.avatar as 'fromUser.avatar'," + "c.id as 'toUser.id',c.realname as 'toUser.realname',c.avatar as 'toUser.avatar' " + "FROM t_demand_comment a " + "LEFT JOIN t_user b ON b.id = a.from_uid " + "LEFT JOIN t_user c ON c.id = a.to_uid " + "WHERE a.demand_id = #{demandId} " + "ORDER BY a.create_date ASC" + "LIMIT #{startNo},#{pageSize}") public List<DemandComment> listDemandComment(@Param("demandId") Long demandId, @Param("startNo") Integer pageNo, @Param("pageSize") Integer pageSize);
這樣整個語句是寫死的,若是我想根據pageNo與pageSize是否爲空來判斷是否須要分頁,該怎麼作呢?若是使用xml來配置的話能夠用spring
<when test='startNo!=null and pageSize != null '> LIMIT #{startNo},#{pageSize} </when>
若是是用@Select 這種該如何作呢?方法:用script標籤包圍,而後像xml語法同樣書寫sql
@Mapper public interface DemandCommentMapper extends BaseMapper<DemandComment>{ @Select("<script>" + "SELECT " + "a.id as 'id',a.create_date as 'createDate',a.content as 'content'," + "a.parent_id as 'parentId',a.first_comment_id as 'firstCommentId'," + "b.id as 'fromUser.id',b.realname as 'fromUser.realname',b.avatar as 'fromUser.avatar'," + "c.id as 'toUser.id',c.realname as 'toUser.realname',c.avatar as 'toUser.avatar' " + "FROM t_demand_comment a " + "LEFT JOIN t_user b ON b.id = a.from_uid " + "LEFT JOIN t_user c ON c.id = a.to_uid " + "WHERE a.demand_id = #{demandId} " + "ORDER BY a.create_date ASC " + "<if test='startNo!=null and pageSize != null '>" + "LIMIT #{startNo},#{pageSize}" + "</if>" + "</script>") public List<DemandComment> listDemandComment(@Param("demandId") Long demandId, @Param("startNo") Integer pageNo, @Param("pageSize") Integer pageSize);
項目實例數據庫
@Select("<script>" +"select * from mi_taobao where 1=1" +"<if test='status != null'>" +"and status = #{status}" +"</if>" +"</script>") public List<Taobao> getTaobao(@Param("status") Integer status);
在這裏還碰到一個問題就是報錯:Caused by: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'status' in 'class java.lang.Interger'apache
出現緣由:這裏出現的問題是在DAO方法中定義的參數 與 實體中定義的屬性不一致 致使的。session
解決方案:dao層加@Param("userId")註解便可(實例中就是加上@Param("status"))mybatis
public List<DictItem> selectKeyByUserId(@Param("userId") long userId);app
package com.cc.service; import com.cc.entity.Student; import java.util.List; public interface StudentService { Student findById(int id); List<Student> selectAll(); }
package com.cc.service; import com.cc.dao.StudentMapper; import com.cc.entity.Student; import java.util.List; public class StudentServiceImpl implements StudentService { private StudentMapper studentMapper; public void setStudentMapper(StudentMapper studentMapper) { this.studentMapper = studentMapper; } @Override public Student findById(int id) { return (Student) studentMapper.findById(id); } @Override public List<Student> selectAll() { return studentMapper.selectAll(); } }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--代表引用的數據庫配置文件db.properties--> <context:property-placeholder location="classpath:db.properties"/> <!--配置數據庫--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配置sqlSessionFactoryBean對象,mybatis主要靠的sqlSessionFactoryBean對象 ,裏面配置兩個參數,一個是dataSource,一個是mybatis核心配置文件--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--mybatis核心配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!--配置Mapper--> <bean id="StudentMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <!--主要靠的是那個Mapper具體來實現的--> <property name="mapperInterface" value="com.cc.dao.StudentMapper"></property> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> <!--配置StudentService--> <bean id="studentService" class="com.cc.service.StudentServiceImpl"> <property name="studentMapper" ref="StudentMapper"></property> </bean> </beans>
#mysql jdbc fresh jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root
import com.cc.entity.Student; import com.cc.service.StudentService; import com.cc.service.StudentServiceImpl; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class Testdemo1 { @Test public void test(){ ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentService studentService =ac.getBean("studentService", StudentServiceImpl.class); Student student=studentService.findById(5); System.out.println(student); List<Student> studentList=studentService.selectAll(); for (Student stu: studentList) { System.out.println(stu); } } }
目錄結構以下ide
第一步、導入jar包
<build> <resources> <!-- mapper.xml文件在java目錄下 --> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> </build> <dependencies> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.9</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>Spring</groupId> <artifactId>Spring_mybatis_01</artifactId> <version>1.0-SNAPSHOT</version> <scope>compile</scope> </dependency> </dependencies>
第二步、建立實體類
package cc.entity; public class Student { private int id; private String stuno; private String name; private String classid; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStuno() { return stuno; } public void setStuno(String stuno) { this.stuno = stuno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassid() { return classid; } public void setClassid(String classid) { this.classid = classid; } @Override public String toString() { return "Student{" + "id=" + id + ", stuno='" + stuno + '\'' + ", name='" + name + '\'' + ", classid='" + classid + '\'' + '}'; } }
第三步、建立StudentDao接口,已經其實現類
package cc.dao; import com.cc.entity.Student; public interface StudentDao { Student findById(int id); }
package cc.dao; import com.cc.dao.StudentDao; import com.cc.entity.Student; import org.mybatis.spring.support.SqlSessionDaoSupport; public class StudentImpl extends SqlSessionDaoSupport implements StudentDao { @Override public Student findById(int id) { return (Student) getSqlSession().selectOne("com.cc.dao.StudentMapper.findById",id); } }
第四步、建立映射器接口,已經其mapper配置文件
package cc.dao; import com.cc.entity.Student; public interface StudentMapper { Student findById(int id); }
<?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.cc.dao.StudentMapper"> <select id="findById" resultType="Student" parameterType="int"> SELECT * from student where id = #{id} </select> </mapper>
第五步、實現ApplicationContext配置文件和mybatis核心配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--代表引用的數據庫配置文件db.properties--> <context:property-placeholder location="classpath:db.properties"/> <!--配置數據庫--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配置sqlSessionFactoryBean對象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--mybatis核心配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <bean id="studentDao" class="cc.dao.StudentImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property> </bean> </beans>
<?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.cc.entity"/> </typeAliases> <mappers> <mapper resource="com\cc\mapper\StudentMapper.xml"></mapper> </mappers> </configuration>
第六步、配置數據文件
#mysql jdbc fresh jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root
第七步、在test文件用junit4實現單元測試
import cc.dao.StudentImpl; import com.cc.entity.Student; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { @org.junit.Test public void test(){ ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentImpl stu=ac.getBean("studentDao", StudentImpl.class); Student student=stu.findById(6); System.out.println(student); } }
這種平時都用的不多,因此這裏我就不寫了
第一步、導入依賴配置
<build> <resources> <!-- mapper.xml文件在java目錄下 --> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> </resource> </resources> </build> <dependencies> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>1.0</version> </dependency> <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.9</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-pool</groupId> <artifactId>commons-pool</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>Spring</groupId> <artifactId>Spring_mybatis_01</artifactId> <version>1.0-SNAPSHOT</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> </dependencies>
第二步、編寫實體類
package cc.entity; public class Student { private int id; private String stuno; private String name; private String classid; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getStuno() { return stuno; } public void setStuno(String stuno) { this.stuno = stuno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClassid() { return classid; } public void setClassid(String classid) { this.classid = classid; } @Override public String toString() { return "Student{" + "id=" + id + ", stuno='" + stuno + '\'' + ", name='" + name + '\'' + ", classid='" + classid + '\'' + '}'; } }
第三步、配置StudentMapper接口
package cc.dao; import com.cc.entity.Student; public interface StudentMapper { Student findById(int id); }
第四步、配置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="cc.dao.StudentMapper"> <select id="findById" resultType="Student" parameterType="int"> SELECT * from student where id = #{id} </select> </mapper>
<?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> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <package name="com.cc.entity"/> </typeAliases> <mappers> <mapper resource="com\cc\mapper\StudentMapper.xml"></mapper> </mappers> </configuration>
第五步、配置數據庫文件
#mysql jdbc fresh jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/fresh?useUnicode=true&characterEncoding=UTF-8 jdbc.username=root jdbc.password=root
第六步、配置ApplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="cc"></context:component-scan> <!--代表引用的數據庫配置文件db.properties--> <context:property-placeholder location="classpath:db.properties"/> <!--配置數據庫--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配置sqlSessionFactoryBean對象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="cc/mapper/*.xml"></property> <!--mybatis核心配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!--配置接口掃描--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cc.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!--配置事務--> </beans>
第七步、編寫測試類
import cc.service.StudentService; import com.cc.entity.Student; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Testone { @Test public void test(){ ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml"); StudentService studentService = (StudentService) ac.getBean("studentService"); Student student=studentService.findById(4); System.out.println(student); } }