【问题标题】:SQL / Hibernate insert only if url not existsSQL / Hibernate 仅在 url 不存在时插入
【发布时间】:2020-07-01 13:43:35
【问题描述】:

我有一个 url 列表和一个包含 url 的表。如果 url 不在表格中,我只想插入。

Data in the Table: 
|id | url | ... |
|---| --- | --- |
| 1 | example.com | ... | 

List<String> urls = new ArrayList<>()
urls.add("example.com/");
urls.add("example.com/#");
urls.add("www.example.com/");
urls.add("https://www.example.com/");
urls.add("example.net");

插入后数据表应包含:

Data in the Table: 
|id | url | ... |
|---| --- | --- |
| 1 | example.com | ... | 
| 2 | example.net | ... |

我目前的尝试是创建一个方法 findByURL(url):List 并为列表中的每个 URL 调用此方法。如果返回的列表为空,我将 url 插入表中,但不幸的是,我的语句在 example.com 和 example.com 之间产生了差异#

@Table(name = "url_to_edit")
@NamedQueries({
        @NamedQuery(name= UrlToEdit.FIND_BY_URL, query = "select urlToEdit from UrlToEdit urlToEdit where urlToEdit.url = :url")
})
@NoArgsConstructor
public class UrlToEdit { ... }

使用我当前的解决方案,该表包含以下行:

Data in the Table: 
|id | url | ... |
|---| --- | --- |
| 1 | example.com | ... | 
| 2 | example.com/ | ... | 
| 3 | example.com/# | ... | 
| 4 | www.example.com/ | ... | 
| 5 | https://www.example.com/ | ... | 
| 6 | example.net | ... | 


怎么在sql里说是一样的呢?或者我需要某种预解析器? 是否可以进行批量插入?我当前的代码一个接一个地插入。

编辑:我有来自一个主机的多个 url。我无法追踪主机名。 例如example.com/test/example.com/test/# 和 example.com/# 等

【问题讨论】:

    标签: java sql hibernate mariadb


    【解决方案1】:

    我认为你应该在将 URL 存储到数据库之前对其进行转换;这样,您的所有数据都将被规范化,您不必手动检查每一行。对表中的 url 列使用 UNIQUE 约束也会有所帮助。

    就转换而言,我认为(不确定)以下正则表达式可能有效:

     Pattern URL_REGEX = Pattern.compile("(?:https?:\\/\\/)?(www\\.)?([^\\/]+).*");
     String url = "http://www.example.com/xxx";
     Matcher matcher = URG_REGEX.matcher(url);
     if (matcher.matches()) {
        url = matcher.group(2);
     } 
    

    注意:我调整了正则表达式以适应您的数据,但我不认为 example.comwww.example.com 是同一个 URL。

    【讨论】:

    • 字段 URL 是唯一的。我已将我们的想法添加到我的代码中。我的网址现在总是以 www 开头,总是没有任何 / 或 #。 and you won't have to check every row manually 可以举个例子吗?如果我没有所有的检查要做,我将不胜感激。
    • 我的意思是,如果你所有的 url 在数据库中都被规范化了,那么检查给定 url(也被规范化)是否已经存在的方法非常简单,只需 findByUrl。
    【解决方案2】:

    也许你可以查看之前是否存在:

    select count(urlToEdit) from UrlToEdit urlToEdit where urlToEdit.url like %:url%

    如果计数器为零,则可以插入

    【讨论】:

    • url1:example.com/ url2:example.com/test/ url2 在数据库中。如果我理解查询正确,如果我在第一个 url 之后询问,结果将是一个。但它应该为零。
    猜你喜欢
    • 2018-06-26
    • 1970-01-01
    • 2016-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多