Hibernate仅插入数据库新记录

时间:2017-12-08 12:49:26

标签: java mysql hibernate

我正在尝试将一些对象写入数据库,我编写了以下代码,它工作正常,但问题是因为我使用的是while循环,hibernate将每个对象视为一个新记录,从而导致数据库充满已存在的价值

我的问题是,我可以使用哪种注释或技术只将新记录(新对象的值)写入数据库,而不必再次写入相同的对象(如果不存在则仅插入)

这是我的代码

<?php
/**
* 
*/
class Auth extends CI_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('m_login');

    }

    public function index()
    {
        $this->load->view("login");
    }

    public function AksiLogin()
    {
        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $passwordx = md5($password);
        $login = $this->m_login->data_login($username, $passwordx);
        $tes = count($login);
        if ($tes > 0) {
            //ambil detail data
            $row = $this->m_login->data_login($username, $passwordx);
            $level = $row->level;
            //daftarkan session
            $data_session = array('level' => $level);
            $this->session->set_userdata($data_session);
            //direct page
            if ($level == 'superadmin') {
                redirect('superadmin');
            }
            else if ($level == 'admin') {
                redirect('admin');
            }

        }
        else {
            $this->index();
        }
    }

    public function logout()
    {
        $this->session->unset_userdata("login");
        $this->session->unset_userdata("username");
        redirect ('index.php/auth');
    }
    }
?>

2 个答案:

答案 0 :(得分:2)

您的问题发生了,因为在每个循环中您创建一个新实体并持久保存它,然后您提交并关闭会话,因此当在第二个循环中开始新事务时,在已经存在的实体和第二个实体之间没有引用,所以将创建新的实体。

您需要重新找到您的实体,如果存在则更新它,否则创建新实体并保留它。

该代码将解决您的问题

 public class Parser {
    public static void logParser() throws IOException {
        // Creating the configuration object
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");
        // Ccreating the session factory object
        SessionFactory factory = cfg.buildSessionFactory();
        String logFileName = "example.txt";
        File logfile = new File("fileName");
        Scanner scanner = new Scanner(new File(fileName), "UTF-8");
        // here is the session object
        Session session = factory.openSession();
        // transaction
        Transaction t = session.beginTransaction();

        while (scanner.hasNext()) {
            String s = scanner.nextLine();
            if (s.startsWith("Start")) {
                String[] logArray = s.split("\\|");
                System.out.println(Arrays.toString(logArray));
                Query query = session.createQuery("FROM " + getTableName() + " Where  your condition "); // use unique filed 
                List<NetGroup> list = query.list();
                if(list.size()==0){
                    NetGroup ng =new NetGroup();
                }else{
                    ng =list.get(0);
                }
               ng.setNetGroup(logArray[2]);

                session.saveOrUpdate(ng);
                System.out.println("Successfully created an object and wrote its values into database ");
                System.out.println();
            }
        }
        session.close();
        t.commit();
        scanner.close();
        System.out.println("Successfully updated the Data Base");
    }
}

确保放置有效条件而不是&#34;您的条件&#34;

答案 1 :(得分:0)

我认为你可以使用那里的主键概念来删除重复的行并使用saveOrUpdate方法。

如果我们使用hibernate API,那么类中应该有一个PK。

session.saveOrUpdate(纳克);

上面的方法在主键的基础上检查记录,如果DB中不存在PK那么它会激活插入查询(如果存在)然后它更新相同的记录而不是插入新记录。

public class NetGroup

{

private int primaryKeyId;

public int getprimaryKeyId() {
        return primaryKeyId;
    }

    public void setprimaryKeyId(int primaryKeyId) {
        this.primaryKeyId = primaryKeyId;
    }

}