Maven文件配置解析和常见内容
2014-07-21 18:01
676 查看
我们先看一个简单的例子:
[html] view
plaincopy
<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/maven-v4_0_0.xsd">
<!-- maven model version -->
<modelVersion>4.0.0</modelVersion>
<!-- project group id & artifact id -->
<groupId>com.freesoft.mvn-webapp</groupId>
<artifactId>mvnwebapp</artifactId>
<!-- packing type -->
<packaging>war</packaging>
<!-- version -->
<version>1.0-SNAPSHOT</version>
<name>mvnwebapp Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>mvnwebapp</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<tomcat-url>http://localhost:8080/manager/html</tomcat-url>
<server>tomcat_localtest</server>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<struts.version>2.3.15</struts.version>
<mysql.version>5.1.29</mysql.version>
<hibernate.version>4.3.1.Final</hibernate.version>
</properties>
</project>
下面分段讲解。
依赖关系。实际上pom之间存在好三种关系:继承、依赖、聚合。我们先讲依赖,这也是最重要的关系。
我们可能经常会遇到这样一个问题:我们的项目有两个依赖项:A & B,而且A和B同时依赖了C,但不是同一个版本。那么我们怎么办呢?
[html] view
plaincopy
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</plugin>
</plugins>
</reporting>
然后运行:mvn project-info-reports:dependencies,来查看依赖项报告。
如果我们需要在某个dependency中去除某个依赖项,直接这样即可:
[html] view
plaincopy
<!-- Struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts.version}</version>
<exclusions>
<exclusion>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</exclusion>
</exclusions>
</dependency>
我的repository下面有个例子就直接拿来用了:
[html] view
plaincopy
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream-parent</artifactId>
<version>1.4.3</version>
</parent>
<artifactId>xstream</artifactId>
<packaging>jar</packaging>
<name>XStream Core</name>
其中的parent表示父pom是com.thoughtworks.xstream的xstream-parent的1.4.3版本。继承关系比较简单,这里不做过多介绍。
我们可以通过一个大的项目来整合各个小的模块:
[html] view
plaincopy
<modules>
<module>my-app</module>
</modules>
属性表述类似于EL表达式,ANT中也同样有,所以我们的properties字段可以这样使用:
[html] view
plaincopy
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
Plugin的配置如下:
[html] view
plaincopy
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<tomcat-url>http://localhost:8080/manager/html</tomcat-url>
<server>tomcat_localtest</server>
</configuration>
</plugin>
</plugins>
</pluginManagement>
我们可以看到同样要哟偶groupId、artifactId、version还有一些配置参数。
指定你在Build时需要的资源文件:
[html] view
plaincopy
<resources>
<resource>
<targetPath>WEB-INF/resource</targetPath>
<!-- 不对文件中的表达式进行处理 -->
<filtering>false</filtering>
<directory>${basedir}/src/test/resources</directory>
<includes>
<include>include.xml</include>
</includes>
<excludes>
<exclude>exclude.xml</exclude>
</excludes>
</resource>
</resources>
ok,基本上就是这么多,后续有什么疑问也请大家留言。
在dependencies中添加:
[html] view
plaincopy
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.18</version>
</dependency>
<!-- Struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts.version}</version>
</dependency>
然后添加properties段:
[html] view
plaincopy
<properties>
<struts.version>2.3.15</struts.version>
</properties>
去WEB-INF目录找到web.xml文件并添加:
[html] view
plaincopy
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在src/main/java目录下添加Action:
[java] view
plaincopy
package com.freesoft.action;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private String username;
private String password;
@Override
public String execute() throws Exception {
return super.execute();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
去src/main/resources目录添加struts.xml文件:
[html] view
plaincopy
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="test" class="com.freesoft.action.TestAction">
<result>/result.jsp</result>
</action>
</package>
</struts>
最后添加两个jsp,其中一个test.jsp
[html] view
plaincopy
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'input.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<s:form action="test.action">
<s:textfield name="username" label="username"></s:textfield>
<s:password name="password" label="password"></s:password>
<s:submit value="submit"></s:submit>
</s:form>
</body>
</html>
最后建立一个result.jsp
[html] view
plaincopy
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'input.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<s:property value="username"/><br>
<s:property value="password"/><br>
</body>
</html>
选择新建一个Maven Debug Configuration,然后goals输入tomcat7:redeploy即可。
需要调试的时候修改tomcat.bat(Windows下)或者tomcat.sh(linux下)文件,其中windows下修改为:
[plain] view
plaincopy
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
然后启动Tomcat,MyEclipse打开远程调试即可调试程序。
首先我们集成MySQL的数据库驱动,我们在pom.xml中添加:
[html] view
plaincopy
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
同样修改pom.xml:
[html] view
plaincopy
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
properties段:
[html] view
plaincopy
<properties>
<struts.version>2.3.15</struts.version>
<mysql.version>5.1.29</mysql.version>
<hibernate.version>4.3.1.Final</hibernate.version>
</properties>
在/src/resource中添加hibernate.cfg.xml,内容是:
[html] view
plaincopy
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!-- 连接url -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<!-- 用户名 -->
<property name="connection.username">root</property>
<!-- 密码 -->
<property name="connection.password">root</property>
<!-- 驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<!-- <property name="format_sql">true</property> -->
<mapping resource="hbm/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
然后添加源代码目录:src/test/java和src/test/resources,并且将其加入到工程的源代码目录中。
添加hbm.xml:
[html] view
plaincopy
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.freesoft.bean.User" table="user" catalog="hibernate">
<id name="id" type="long">
<column name="id" />
<generator class="increment" />
</id>
<property name="username" type="string">
<column name="username" length="50" />
</property>
<property name="password" type="string">
<column name="password" length="50" />
</property>
<property name="telephone" type="integer">
<column name="telephone" />
</property>
<property name="gender" type="character">
<column name="gender" length="1" />
</property>
<property name="graduation" type="boolean">
<column name="graduation" />
</property>
<property name="birthday" type="date">
<column name="birthday" length="10" />
</property>
<property name="marryTime" type="timestamp">
<column name="marryTime" length="19" />
</property>
<property name="file" type="blob">
<column name="file" />
</property>
</class>
</hibernate-mapping>
然后编写测试代码。
[java] view
plaincopy
package com.freesoft.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Timestamp;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.freesoft.bean.User;
import com.freesoft.util.db.HibernateUtil;
public class TestUser {
@Test
public void testAdd() {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
User user = new User();
user.setUsername("张三");
user.setPassword("password");
user.setGender('F');
user.setBirthday(new java.sql.Date(new java.util.Date().getTime()));
user.setGraduation(true);
user.setTelephone(1234567890);
user.setMarryTime(new Timestamp(new java.util.Date().getTime()));
InputStream ins = new FileInputStream(new File("src/test/resources/test.xml"));
Blob file = Hibernate.getLobCreator(session).createBlob(ins, ins.available());
user.setFile(file);
tx = session.beginTransaction();
session.save(user);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}
@Test
public void testGet() {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
User user = (User) session.get(User.class, 1L);
Blob file = user.getFile();
long length = file.length();
byte[] buf = file.getBytes(1, (int) length);
OutputStream outs = new FileOutputStream(new File("src/test/resources/111.xml"));
outs.write(buf);
outs.flush();
outs.close();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}
}
注意这里为了避免由于文件内容是中文引起的"Data too long for column 'file' at row 1"错误,我没有将file字段设置为byte[]而是设置为了Blob类型。
再新建一个maven的debug configuration,目录选择工程目录,goals选择test,然后run。
[html] view
plaincopy
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.2.RELEASE</version>
<scope>runtime</scope>
</dependency>
</dependencies>
[html] view
plaincopy
<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/maven-v4_0_0.xsd">
<!-- maven model version -->
<modelVersion>4.0.0</modelVersion>
<!-- project group id & artifact id -->
<groupId>com.freesoft.mvn-webapp</groupId>
<artifactId>mvnwebapp</artifactId>
<!-- packing type -->
<packaging>war</packaging>
<!-- version -->
<version>1.0-SNAPSHOT</version>
<name>mvnwebapp Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>mvnwebapp</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<tomcat-url>http://localhost:8080/manager/html</tomcat-url>
<server>tomcat_localtest</server>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<properties>
<struts.version>2.3.15</struts.version>
<mysql.version>5.1.29</mysql.version>
<hibernate.version>4.3.1.Final</hibernate.version>
</properties>
</project>
下面分段讲解。
1. 基本信息
modelVersion | Maven模块版本,目前我们一般都取值4.0.0 |
groupId | 整个系统的名称。 |
artifactId | 子模块名称。 |
packaging | 打包类型,可取值:jar,war等等,这个配置用于package的phase,具体可以参见package运行的时候启动的plugin,后面有机会我们会讲述如何配置打包的插件。 |
2. dependencies
依赖关系。实际上pom之间存在好三种关系:继承、依赖、聚合。我们先讲依赖,这也是最重要的关系。groupId | 依赖项的groupId |
artifactId | 依赖项的artifactId |
version | 依赖项的版本 |
scope | 依赖项的适用范围: compile,缺省值,适用于所有阶段,会随着项目一起发布。 provided,类似compile,期望JDK、容器或使用者会提供这个依赖。如servlet.jar。 runtime,只在运行时使用,如JDBC驱动,适用运行和测试阶段。 test,只在测试时使用,用于编译和运行测试代码。不会随项目发布。 system,类似provided,需要显式提供包含依赖的jar,Maven不会在Repository中查找它。 之前例子里的junit就只用在了test中。 |
exclusions | 排除项目中的依赖冲突时使用。 |
2.1 关于排除依赖冲突
我们可能经常会遇到这样一个问题:我们的项目有两个依赖项:A & B,而且A和B同时依赖了C,但不是同一个版本。那么我们怎么办呢?
2.1.1 添加检查插件
[html] viewplaincopy
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</plugin>
</plugins>
</reporting>
然后运行:mvn project-info-reports:dependencies,来查看依赖项报告。
2.1.2 去除依赖项
如果我们需要在某个dependency中去除某个依赖项,直接这样即可:[html] view
plaincopy
<!-- Struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts.version}</version>
<exclusions>
<exclusion>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</exclusion>
</exclusions>
</dependency>
3. 继承
我的repository下面有个例子就直接拿来用了:[html] view
plaincopy
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream-parent</artifactId>
<version>1.4.3</version>
</parent>
<artifactId>xstream</artifactId>
<packaging>jar</packaging>
<name>XStream Core</name>
其中的parent表示父pom是com.thoughtworks.xstream的xstream-parent的1.4.3版本。继承关系比较简单,这里不做过多介绍。
4. 聚合
我们可以通过一个大的项目来整合各个小的模块:[html] view
plaincopy
<modules>
<module>my-app</module>
</modules>
5. 属性
属性表述类似于EL表达式,ANT中也同样有,所以我们的properties字段可以这样使用:[html] view
plaincopy
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
6. 构建
6.1 plugin
Plugin的配置如下:[html] view
plaincopy
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<tomcat-url>http://localhost:8080/manager/html</tomcat-url>
<server>tomcat_localtest</server>
</configuration>
</plugin>
</plugins>
</pluginManagement>
我们可以看到同样要哟偶groupId、artifactId、version还有一些配置参数。
6.2 resource
指定你在Build时需要的资源文件:[html] view
plaincopy
<resources>
<resource>
<targetPath>WEB-INF/resource</targetPath>
<!-- 不对文件中的表达式进行处理 -->
<filtering>false</filtering>
<directory>${basedir}/src/test/resources</directory>
<includes>
<include>include.xml</include>
</includes>
<excludes>
<exclude>exclude.xml</exclude>
</excludes>
</resource>
</resources>
ok,基本上就是这么多,后续有什么疑问也请大家留言。
Maven继承SSH
1. 集成Struts2
1.1 修改pom.xml
在dependencies中添加:[html] view
plaincopy
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.18</version>
</dependency>
<!-- Struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts.version}</version>
</dependency>
然后添加properties段:
[html] view
plaincopy
<properties>
<struts.version>2.3.15</struts.version>
</properties>
1.2 修改web.xml
去WEB-INF目录找到web.xml文件并添加:[html] view
plaincopy
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
1.3 添加Action
在src/main/java目录下添加Action:[java] view
plaincopy
package com.freesoft.action;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private String username;
private String password;
@Override
public String execute() throws Exception {
return super.execute();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
1.4 添加struts.xml
去src/main/resources目录添加struts.xml文件:[html] view
plaincopy
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="test" class="com.freesoft.action.TestAction">
<result>/result.jsp</result>
</action>
</package>
</struts>
1.5 添加jsp
最后添加两个jsp,其中一个test.jsp[html] view
plaincopy
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'input.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<s:form action="test.action">
<s:textfield name="username" label="username"></s:textfield>
<s:password name="password" label="password"></s:password>
<s:submit value="submit"></s:submit>
</s:form>
</body>
</html>
最后建立一个result.jsp
[html] view
plaincopy
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'input.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<s:property value="username"/><br>
<s:property value="password"/><br>
</body>
</html>
1.6 运行和调试
选择新建一个Maven Debug Configuration,然后goals输入tomcat7:redeploy即可。需要调试的时候修改tomcat.bat(Windows下)或者tomcat.sh(linux下)文件,其中windows下修改为:
[plain] view
plaincopy
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
然后启动Tomcat,MyEclipse打开远程调试即可调试程序。
2. 集成Hibernate
2.1 集成MySQL Driver
首先我们集成MySQL的数据库驱动,我们在pom.xml中添加:[html] view
plaincopy
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
2.2 集成Hibernate
同样修改pom.xml:[html] view
plaincopy
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
properties段:
[html] view
plaincopy
<properties>
<struts.version>2.3.15</struts.version>
<mysql.version>5.1.29</mysql.version>
<hibernate.version>4.3.1.Final</hibernate.version>
</properties>
2.3 添加hibernate.cfg.xml
在/src/resource中添加hibernate.cfg.xml,内容是:[html] view
plaincopy
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<!-- 连接url -->
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<!-- 用户名 -->
<property name="connection.username">root</property>
<!-- 密码 -->
<property name="connection.password">root</property>
<!-- 驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<!-- <property name="format_sql">true</property> -->
<mapping resource="hbm/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
然后添加源代码目录:src/test/java和src/test/resources,并且将其加入到工程的源代码目录中。
2.4 添加测试
添加hbm.xml:[html] view
plaincopy
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.freesoft.bean.User" table="user" catalog="hibernate">
<id name="id" type="long">
<column name="id" />
<generator class="increment" />
</id>
<property name="username" type="string">
<column name="username" length="50" />
</property>
<property name="password" type="string">
<column name="password" length="50" />
</property>
<property name="telephone" type="integer">
<column name="telephone" />
</property>
<property name="gender" type="character">
<column name="gender" length="1" />
</property>
<property name="graduation" type="boolean">
<column name="graduation" />
</property>
<property name="birthday" type="date">
<column name="birthday" length="10" />
</property>
<property name="marryTime" type="timestamp">
<column name="marryTime" length="19" />
</property>
<property name="file" type="blob">
<column name="file" />
</property>
</class>
</hibernate-mapping>
然后编写测试代码。
[java] view
plaincopy
package com.freesoft.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Timestamp;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.freesoft.bean.User;
import com.freesoft.util.db.HibernateUtil;
public class TestUser {
@Test
public void testAdd() {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
User user = new User();
user.setUsername("张三");
user.setPassword("password");
user.setGender('F');
user.setBirthday(new java.sql.Date(new java.util.Date().getTime()));
user.setGraduation(true);
user.setTelephone(1234567890);
user.setMarryTime(new Timestamp(new java.util.Date().getTime()));
InputStream ins = new FileInputStream(new File("src/test/resources/test.xml"));
Blob file = Hibernate.getLobCreator(session).createBlob(ins, ins.available());
user.setFile(file);
tx = session.beginTransaction();
session.save(user);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}
@Test
public void testGet() {
Session session = HibernateUtil.getSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
User user = (User) session.get(User.class, 1L);
Blob file = user.getFile();
long length = file.length();
byte[] buf = file.getBytes(1, (int) length);
OutputStream outs = new FileOutputStream(new File("src/test/resources/111.xml"));
outs.write(buf);
outs.flush();
outs.close();
tx.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
HibernateUtil.closeSession(session);
}
}
}
注意这里为了避免由于文件内容是中文引起的"Data too long for column 'file' at row 1"错误,我没有将file字段设置为byte[]而是设置为了Blob类型。
再新建一个maven的debug configuration,目录选择工程目录,goals选择test,然后run。
3. 集成Spring
[html] viewplaincopy
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.2.RELEASE</version>
<scope>runtime</scope>
</dependency>
</dependencies>
相关文章推荐
- Linux网络配置文件常见配置项内容解析
- C# 解析配置文件内容
- Maven配置文件全解析
- [转]C# 解析配置文件内容 System.Configuration
- maven的pom.xml配置文件中常用的配置标签解析
- maven项目的pom文件内容配置详解
- [转]C# 解析配置文件内容 System.Configuration
- Java 获取*.properties配置文件中的内容 ,常见的两种方法
- Dubbo和Spring结合配置文件内容解析为bean的过程
- 【开源.NET】轻量级内容管理框架Grissom.CMS(第三篇解析配置文件和数据以转换成 sql)
- maven的pom.xml配置文件中常用的配置标签解析(2018-03-13)
- IPtalbes配置文件内容解析
- maven学习教程(二)—— 常见命令、配置解析、HelloWorld
- ideal+maven+scala配置spark的pom.xml文件内容,直接写spark代码
- [转]C# 解析配置文件内容 System.Configuration
- radvd.conf RADVD配置文件内容部分解析
- 配置scut协议生成器的时候需要配置iis,出现常见错误——Win7中IIS出现“HTTP 错误 404.17 - Not Found 请求的内容似乎是脚本,因而将无法由静态文件处理程序来处理。
- eclipse中maven配置文件pom.xml解析报错
- SVN检出Maven项目 配置文件 ---解决tomcat无法加载解析项目
- J2SE桌面小程序包含配置文件打成jar包引出的一系列问题(2)-maven打jar包 getResource为null问题解析