日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

mybatis集成JNDI【注部署项目后测试代码在jsp或servlet中】

發布時間:2024/2/28 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mybatis集成JNDI【注部署项目后测试代码在jsp或servlet中】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

pom.xml

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.henu</groupId><artifactId>mybatis03_JNDI</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>mybatis03_JNDI Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target></properties><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.10</version></dependency><!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api --><dependency><groupId>javax.servlet</groupId><artifactId>jsp-api</artifactId><version>2.0</version><scope>provided</scope></dependency></dependencies><build><finalName>mybatis03_JNDI</finalName><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build> </project>

?User

package com.henu.bean;import java.io.Serializable; import java.util.Date;public class User implements Serializable {private Integer id;private String username;private Date birthday;private String sex;private String address;public User() {}public User(Integer id, String username, Date birthday, String sex, String address) {this.id = id;this.username = username;this.birthday = birthday;this.sex = sex;this.address = address;}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 getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", birthday=" + birthday +", sex='" + sex + '\'' +", address='" + address + '\'' +'}';} }

QueryVo

package com.henu.bean;import java.util.List;/*** @author George* @description**/ public class QueryVo {private User user;private List<Integer> ids;public User getUser() {return user;}public void setUser(User user) {this.user = user;}public List<Integer> getIds() {return ids;}public void setIds(List<Integer> ids) {this.ids = ids;} }

UserDao

package com.henu.dao;import com.henu.bean.QueryVo; import com.henu.bean.User;import java.util.List;public interface UserDao {/*** 查詢所有* @return*/List<User> findAll();/*** 根據userId查詢用戶* @param userId*/User findUserById(Integer userId);/*** 根據名稱模糊查詢用戶* @param username*/List<User> findUserByName(String username);/*** 根據queryVo中的條件查詢用戶* @param queryVo* @return*/List<User> findUserByVo(QueryVo queryVo);/*** 根據不同的條件查詢用戶* @param user* @return*/List<User> findUserByCondition(User user);/*** 根據queryvo中提供的id集合,查詢用戶信息* @param vo* @return*/List<User> findUserInIds(QueryVo vo); }

SqlMapConfig.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><typeAliases><package name="com.henu.bean"></package></typeAliases><environments default="mysql"><environment id="mysql"><transactionManager type="JDBC"></transactionManager><dataSource type="JNDI"><!--java:comp/env固定,后面跟context.xml中的name值--><property name="data_source" value="java:comp/env/jdbc/mybatis"></property></dataSource></environment></environments><mappers><mapper resource="com/henu/dao/UserDao.xml"></mapper></mappers></configuration>

jdbcConfig.properties

driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8 username=root password=123456

log4j.properties

# Global logging configuration log4j.rootLogger=error, stdout # MyBatis logging configuration... log4j.logger.cn.wolfcode.mybatis=TRACE # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

UserDao.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.henu.dao.UserDao"><!--配置 查詢結果的列名稱和實體類的屬性名的對應關系--><resultMap id="map" type="user"><!--主鍵字段的對應--><id property="id" column="id" /><!--非主鍵字段的對應 --><result property="username" column="username"/><result property="birthday" column="birthday"/><result property="sex" column="sex"/><result property="address" column="address"/></resultMap><!--了解的內容,抽取重復的sql語句--><sql id="defaultUser">select * from user</sql><!--配置查詢所有--><!--id為方法名稱--><select id="findAll" resultType="com.henu.bean.User"><include refid="defaultUser"></include></select><!--配置根據id查詢用戶--><select id="findUserById" parameterType="int" resultType="com.henu.bean.User">select * from user where id=#{id};</select><!--配置根據name模糊查詢用戶--><select id="findUserByName" parameterType="String" resultType="com.henu.bean.User"><!--select * from user where username like #{username};開發中采用#{username},因為這種采用的是預編譯-->select * from user where username like '%${value}%';</select><!--配置根據QueryVo查詢用戶--><select id="findUserByVo" parameterType="com.henu.bean.QueryVo" resultType="com.henu.bean.User"><!--select * from user where username like #{username};開發中采用#{username},因為這種采用的是預編譯-->select * from user where username like #{user.username}</select><!--配置根據不同條件查詢用戶【注不能再sql語句后加 ; 】--><select id="findUserByCondition" resultMap="map" parameterType="com.henu.bean.User"><!--select * from user where 1=1<if test="username != null">and username = #{username}</if><if test="sex != null">and sex = #{sex}</if>-->select * from user<where><if test="username != null">and username = #{username}</if><if test="sex != null">and sex = #{sex}</if></where></select><!--根據queryvo中的ID集合實現查詢用戶列表--><select id="findUserInIds" resultType="user" parameterType="queryvo"><include refid="defaultUser"></include><where><if test="ids != null and ids.size>0"><foreach collection="ids" open="and id in (" close=")" item="id" separator=",">#{id}</foreach></if></where></select></mapper>

context.xml

<?xml version="1.0" encoding="UTF-8"?> <Context><!--name 數據源名稱type 數據源類型auth 數據源提供者maxActive 最大活動數maxWait 最大等待時間maxIdle 最大空閑數username 用戶名password 密碼driverClassName 驅動類url 鏈接url字符串--><Resourcename="jdbc/mybatis"auth="Container"type="javax.sql.DataSource"driverClassName="com.mysql.jdbc.Driver"url="jdbc:mysql://localhost:3306/mybatis"username="root"password="123456"maxActive="20"maxIdle="10"maxWait="-1"/> </Context>

MybatisTest

package com.henu.test;import com.henu.bean.QueryVo; import com.henu.bean.User; import com.henu.dao.UserDao; 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 java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.List;/*** @author George* @description**/ public class MybatisTest {private InputStream in;private SqlSession sqlSession;private UserDao userDao;@Before //用于測試方法執行之前執行public void init() throws IOException {in = Resources.getResourceAsStream("SqlMapConfig.xml");//2.創建SqlSessionFactory工廠SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);//3.使用工廠生成SqlSession對象sqlSession = factory.openSession();//4.使用SqlSession創建Dao接口的代理對象userDao = sqlSession.getMapper(UserDao.class);}@After //用于測試方法執行之后執行public void destory() throws IOException {sqlSession.close();in.close();}/*** 查詢全部*/@Testpublic void findAllTest() throws IOException {//1.讀取配置文件InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");//2.創建SqlSessionFactory工廠SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();SqlSessionFactory factory = builder.build(in);//3.使用工廠生成SqlSession對象SqlSession session = factory.openSession();//4.使用SqlSession創建Dao接口的代理對象UserDao userDao = session.getMapper(UserDao.class);//5.使用代理對象執行方法List<User> list = userDao.findAll();for (User user : list) {System.out.println(user);}//6.釋放資源session.close();in.close();}@Testpublic void findUserByIdTest() throws IOException {System.out.println(userDao.findUserById(44));}@Testpublic void findUserByNameTest() throws IOException {/*List<User> users = userDao.findUserByName("%卡%");*/List<User> users = userDao.findUserByName("卡");for (User user : users) {System.out.println(user);}}@Testpublic void findUserByQuertVoTest() throws IOException {QueryVo queryVo = new QueryVo();User user = new User();user.setUsername("%卡%");queryVo.setUser(user);List<User> users = userDao.findUserByVo(queryVo);for (User u : users) {System.out.println(u);}}@Testpublic void findUserByConditon() throws IOException {User user = new User();user.setUsername("卡哇伊");user.setSex("女");List<User> users = userDao.findUserByCondition(user);for (User u : users) {System.out.println(u);}}/*** 測試foreach標簽的使用* @throws IOException*/@Testpublic void findUserInIdsTest() throws IOException {QueryVo queryVo = new QueryVo();List<Integer> list = new ArrayList<Integer>();list.add(41);list.add(43);list.add(45);queryVo.setIds(list);List<User> users = userDao.findUserInIds(queryVo);for (User u : users) {System.out.println(u);}}}

?

【注】測試結果需要在tomcat啟動部署項目后,將代碼在jsp中顯示

如下:

index.jsp

<%@ page import="java.io.InputStream" %> <%@ page import="org.apache.ibatis.io.Resources" %> <%@ page import="org.apache.ibatis.session.SqlSessionFactory" %> <%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %> <%@ page import="org.apache.ibatis.session.SqlSession" %> <%@ page import="com.henu.dao.UserDao" %> <%@ page import="java.util.List" %> <%@ page import="com.henu.bean.User" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <body> <h2>Hello World!</h2><%System.out.println("<---------------------------------------------------------------------->");InputStream in1 = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactoryBuilder builder1 = new SqlSessionFactoryBuilder();SqlSessionFactory factory1 = builder1.build(in1);SqlSession sqlSession1 = factory1.openSession();UserDao userDao1 = sqlSession1.getMapper(UserDao.class);User user = new User();user.setUsername("卡哇伊");user.setSex("女");List<User> users = userDao1.findUserByCondition(user);for (User u : users) {System.out.println(u);}sqlSession1.close();in1.close();// 等多種測試類中方法。 %> </body> </html>

?

總結

以上是生活随笔為你收集整理的mybatis集成JNDI【注部署项目后测试代码在jsp或servlet中】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。