首页 > 代码库 > maven(04)--一个简单的项目

maven(04)--一个简单的项目

简单介绍

  一个maven项目,使用hibernate框架,实现向mysql数据库中添加和获取操作,其他操作也是类似

  如果你没有hibernate,那么也不要紧,这里主要介绍如何在一个maven项目中引入框架

项目流程

  1、新建一个maven项目,项目命名为maven-ch04

  2、添加相关依赖,如junit、hibernate、mysql驱动、log4j

  pom.xml文件添加以下依赖(如果你是第一次加这些依赖,那么需要等一会,这时候IDEA会下载一些相关文件)

  如果你不知道如何查找依赖,可以查看maven(02)

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.10.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

  3、在mysql数据可以新建一个数据库,名称为maven

  4、新建实体类User(注意新建包)

package com.simfg.maven.model;
/**
 * Created by SimFG on 2017/5/14.
 */
public class User {
    private int id;
    private String name;
    private String password;

    public User() {
    }

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

  5、在resources文件夹下新建hibernate.cfg.xml(如果没有resource文件夹,则在src下新建;注意修改mysql连接密码;如果你新建数据库名称不为maven,那么你也需要修改连接连接数据库名称)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>

        <!-- 连接数据库 -->
        <property name="connection.username">root</property>
        <!--  mysql的连接密码 -->
        <property name="connection.password">xxxxx</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql:///maven?characterEncoding=UTF8&amp;userSSL=true</property>

        <!-- 配置hibernate的信息 -->
        <!-- hibernate所使用的数据库方言 -->
        <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

        <!-- 执行操作控制台是否打印sql -->
        <property name="show_sql">true</property>
        <!-- 格式化sql语句 -->
        <property name="format_sql">true</property>
        <!-- 指定自动生成策略 -->
        <property name="hbm2ddl.auto">update</property>

        <!-- 指定关联的.hbm.xml -->
        <mapping resource="com/simfg/maven/model/User.hbm.xml"/>

    </session-factory>
</hibernate-configuration>

  6、在该目录下新建一个log4j.properties,内容如下

  如果你想详细了解log4j如何配置,可以参照log4j详解

log4j.rootLogger=WARN, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller‘s file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
# Print only messages of level WARN or above in the package com.foo.
log4j.logger.com.foo=WARN

  7、在User.java这个文件的同一目录下新建一个User.hbm.xml文件(注意修改class标签中name属性,改成你自己命名的包)

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
    <class name="com.simfg.maven.model.User" table="USER">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
    </class>
</hibernate-mapping>

  8、编写一个HibernateUtil.java文件,注意建立相应的包

package com.simfg.maven.util;

import com.simfg.maven.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * Created by SimFG on 2017/5/14.
 */
public class HibernateUtil {

    private static Session session;
    private static Transaction transaction;
    private static SessionFactory sessionFactory;

    public static void startup(){
        // 1:创建一个sessionFactory对象
        StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();
        Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
                .applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
        sessionFactory = metadata.getSessionFactoryBuilder().build();

        // 2:创建一个session对象
        session = sessionFactory.openSession();
        // 3:开启事务
        transaction = session.beginTransaction();
    }

    private static void closeup(){
        // 5:提交事务
        transaction.commit();
        // 6:关闭session
        session.close();
        // 7:关闭sessionFactory
        sessionFactory.close();
    }

    public static void hibernateSave(User user) throws Exception {
        startup();
        session.save(user);
        closeup();

    }
    public static User hibernateQuery(){
        startup();
        String sql = "FROM User u WHERE u.name = ?";
        User user = (User) session.createQuery(sql).setParameter(0,"sim").uniqueResult();
        closeup();
        return user;
    }
}

  9、编写一个DAO,即UserDao.java

package com.simfg.maven.dao;

import com.simfg.maven.model.User;
import com.simfg.maven.util.HibernateUtil;

/**
 * Created by SimFG on 2017/5/14.
 */
public class UserDao{

    public void addUser() {
        try {
            HibernateUtil.hibernateSave(new User("sim","123456"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public User loadByUsername() {
        return HibernateUtil.hibernateQuery();
    }
}

  10、测试,在test中新建一个TestUserDao.java

import com.simfg.maven.dao.UserDao;
import com.simfg.maven.model.User;
import org.junit.Before;
import org.junit.Test;

/**
 * Created by SimFG on 2017/5/14.
 */
public class TestUserDao {
    private UserDao userDao;

    @Before
    public void setup() {
        userDao = new UserDao();
    }

    @Test
    public void add(){
        userDao.addUser();
        System.out.println(userDao.loadByUsername().getName());
    }
}

 运行add,结果如下图

技术分享

  如果你运行项目出现xxx.hbm.xml未找到

  在pom.xml文件加一下代码

<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>
    </build>

 

maven(04)--一个简单的项目